Specifications
If you get this error, you need to make sure that the user that the script runs as has permission
to access the file you are trying to use. Depending on how your server is set up, the script
might be running as the Web server user or as the owner of the directory that the script is in.
On most systems, the script will run as the Web server user. If your script was on a UNIX sys-
tem in the ~/public_html/chapter2/ directory, you would create a world writeable directory
in which to store the order by typing the following:
mkdir ~/orders
chmod 777 ~/orders
Bear in mind that directories and files that anybody can write to are dangerous. You should not
have directories that are accessible directly from the Web as writable. For this reason, our
orders directory is two subdirectories back, above the public_html directory. We will talk
more about security later in Chapter 13, “E-commerce Security Issues.”
Incorrect permission settings is probably the most common thing that can go wrong when
opening a file, but it’s not the only thing. If the file can’t be opened, you really need to know
this so that you don’t try to read data from or write data to it.
If the call to fopen() fails, the function will return false. You can deal with the error in a
more user-friendly way by suppressing PHP’s error message and giving your own:
@ $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, “a”, 1);
if (!$fp)
{
echo “<p><strong> Your order could not be processed at this time. “
.”Please try again later.</strong></p></body></html>”;
exit;
}
The @ symbol in front of the call to fopen() tells PHP to suppress any errors resulting from the
function call. Usually it’s a good idea to know when things go wrong, but in this case we’re
going to deal with that elsewhere. Note that the @ symbol needs to be at the very start of the
line. You can read more about error reporting in Chapter 23, “Debugging.”
The if statement tests the variable $fp to see if a valid file pointer was returned from the
fopen call; if not, it prints an error message and ends script execution. Because the page will
finish here, notice that we have closed the HTML tags to give valid HTML.
The output when using this approach is shown in Figure 2.3.
Using PHP
P
ART I
56
04 7842 CH02 3/6/01 3:37 PM Page 56