13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

66 Chapter 2 Storing <strong>and</strong> Retrieving Data<br />

On most systems, the script runs as the web server user. If your script is on a Unix<br />

system in the ~/public_html/chapter2/ directory, for example, you could create a<br />

world-writeable directory in which to store the order by typing the following:<br />

mkdir ~/orders<br />

chmod 777 ~/orders<br />

Bear in mind that directories <strong>and</strong> files that anybody can write to are dangerous. In particular,<br />

directories that are accessible directly from the <strong>Web</strong> should not be writeable. For<br />

this reason, our orders directory is two subdirectories back, above the public_html<br />

directory.We discuss security more in Chapter 15,“E-commerce Security Issues.”<br />

Incorrect permission setting is probably the most common thing that can go wrong<br />

when opening a file, but it’s not the only thing. If you can’t open the file, you really need<br />

to know this so that you don’t try to read data from or write data to it.<br />

If the call to fopen() fails, the function will return false.You can deal with the<br />

error in a more user-friendly way by suppressing <strong>PHP</strong>’s error message <strong>and</strong> giving your<br />

own:<br />

@ $fp = fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, ‘ab’);<br />

if (!$fp){<br />

echo " Your order could not be processed at this time. "<br />

.Please try again later.";<br />

exit;<br />

}<br />

The @ symbol in front of the call to fopen() tells <strong>PHP</strong> to suppress any errors resulting<br />

from the function call. Usually, it’s a good idea to know when things go wrong, but in<br />

this case we’re going to deal with that problem elsewhere.<br />

You can also write this line as follows:<br />

$fp = @fopen(“$DOCUMENT_ROOT/../orders/orders.txt”, ‘a’);<br />

Using this method tends to make it less obvious that you are using the error suppression<br />

operator, so it may make your code harder to debug.<br />

The method described here is a simplistic way of dealing with errors.We look at a<br />

more elegant method for error h<strong>and</strong>ling in Chapter 7,“Error <strong>and</strong> Exception H<strong>and</strong>ling.”<br />

But one thing at a time.<br />

The if statement tests the variable $fp to see whether a valid file pointer was<br />

returned from the fopen call; if not, it prints an error message <strong>and</strong> ends script execution.<br />

Because the page finishes here, notice that we have closed the HTML tags to give reasonably<br />

valid HTML.<br />

The output when using this approach is shown in Figure 2.3.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!