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.

438 Chapter 19 Interacting with the File System <strong>and</strong> the Server<br />

To ensure that you are not vulnerable, this script uses the is_uploaded_file() <strong>and</strong><br />

move_uploaded_file() functions to make sure that the file you are processing has actually<br />

been uploaded <strong>and</strong> is not a local file such as /etc/passwd.This function is available<br />

from <strong>PHP</strong> version 4.0.3 onward.<br />

Unless you write your upload h<strong>and</strong>ling script carefully, a malicious visitor could provide<br />

his own temporary filename <strong>and</strong> convince your script to h<strong>and</strong>le that file as though<br />

it were the uploaded file. Because many file upload scripts echo the uploaded data back<br />

to the user or store it somewhere that it can be loaded, this could lead to people being<br />

able to access any file that the web server can read.This could include sensitive files such<br />

as /etc/passwd <strong>and</strong> <strong>PHP</strong> source code including your database passwords.<br />

Avoiding Common Upload Problems<br />

Keep the following points in mind when performing file uploads:<br />

n The previous example assumes that users have been authenticated elsewhere.You<br />

shouldn’t allow just anybody to upload files to your site.<br />

n If you are allowing untrusted or unauthenticated users to upload files, it’s a good<br />

idea to be paranoid about the contents of the files.The last thing you want is a<br />

malicious script being uploaded <strong>and</strong> run.You should be careful, not just of the type<br />

<strong>and</strong> contents of the file as we are here, but of the filename itself. It’s a good idea to<br />

rename uploaded files to something you know to be “safe.”<br />

n To mitigate the risk of users “directory surfing” on your server, you can use the<br />

basename() function to modify the names of incoming files. This function will<br />

strip off any directory paths that are passed in as part of the filename, which is a<br />

common attack that is used to place a file in a different directory on your server.<br />

An example of this function is as follows:<br />

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

Saved successfully!

Ooh no, something went wrong!