13.09.2016 Views

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Uploading Files<br />

437<br />

n<br />

UPLOAD_ERR_CANT_WRITE, value 7, means that writing the file to disk failed (introduced<br />

in <strong>PHP</strong> 5.1.0).<br />

If you want to use an older version of <strong>PHP</strong>, you can perform a manual version of some<br />

of these checks using sample code in the <strong>PHP</strong> manual or in older editions of this book.<br />

You also check the MIME type. In this case, we want you to upload text files only, so<br />

test the MIME type by making sure that $_FILES[‘userfile’][‘type’] contains<br />

text/plain.This is really only error checking. It is not security checking.The MIME<br />

type is inferred by the user’s browser from the file extension <strong>and</strong> passed to your server. If<br />

there were some advantage to be obtained by passing a false one, it would not be hard<br />

for a malicious user to do so.<br />

You then check that the file you are trying to open has actually been uploaded <strong>and</strong> is<br />

not a local file such as /etc/passwd.We come back to this topic in a moment.<br />

If that all works out okay, you then copy the file into the include directory.We used<br />

/uploads/ in this example; it’s outside the web document tree <strong>and</strong> therefore a good<br />

place to put files that are to be included elsewhere.<br />

You then open up the file, clean out any stray HTML or <strong>PHP</strong> tags that might be in<br />

the file using the strip_tags() function, <strong>and</strong> write the file back. Finally, you display the<br />

contents of the file so the user can see that her file uploaded successfully.<br />

The results of one (successful) run of this script are shown in Figure 19.2.<br />

In September 2000, an exploit was announced that could allow a cracker to fool <strong>PHP</strong><br />

file upload scripts into processing a local file as if it had been uploaded.This exploit was<br />

documented on the BUGTRAQ mailing list.You can read the official security advisory<br />

at one of the many BUGTRAQ archives, such as http://lists.insecure.org/bugtraq/<br />

2000/Sep/0237.html.<br />

Figure 19.2 After the file is copied <strong>and</strong> reformatted, the uploaded file is displayed<br />

as confirmation to the user that the upload was successful.

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

Saved successfully!

Ooh no, something went wrong!