05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

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

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

as /etc/passwd or /home/rasmus/.forward.You can use the browser-supplied name for<br />

all user interaction, but generate a unique name yourself to actually call the file.For<br />

example:<br />

$browser_name = $_FILES['image']['name'];<br />

$temp_name = $_FILES['image']['tmp_name'];<br />

echo "Thanks for sending me $browser_name.";<br />

$counter++; // persistent variable<br />

$my_name = "image_$counter";<br />

if (is_uploaded_file($temp_name)) {<br />

move_uploaded_file($temp_name, "/web/images/$my_name");<br />

} else {<br />

die("There was a problem processing the file.");<br />

}<br />

Beware of Filling Your Filesystem<br />

Another trap is the size of uploaded files.Although you can tell the browser the maximum<br />

size of file to upload, this is only a recommendation and it cannot ensure that<br />

your script won’t be handed a file of a larger size.The danger is that an attacker will<br />

try a denial of service attack by sending you several large files in one request and filling<br />

up the filesystem in which <strong>PHP</strong> stores the decoded files.<br />

Set the post_max_size configuration option in php.ini to the maximum size (in bytes)<br />

that you want:<br />

post_max_size = 1024768 ; one megabyte<br />

The default 10 MB is probably larger than most sites require.<br />

Surviving register_globals<br />

The default variables_order processes GET and POST parameters before cookies.<br />

This makes it possible for the user to send a cookie that overwrites the global variable<br />

you think contains information on your uploaded file.To avoid being tricked<br />

like this, check the given file was actually an uploaded file using the is_uploaded_<br />

file( ) function.<br />

In this example, the name of the file input element is “uploaded”:<br />

if (is_uploaded_file($_FILES['uploaded_file']['tmp_name'])) {<br />

if ($fp = fopen($_FILES['uploaded_file']['tmp_name'], 'r')) {<br />

$text = fread($fp, filesize($_FILES['uploaded_file']['tmp_name']));<br />

fclose($fp);<br />

// do something with the file's contents<br />

}<br />

}<br />

<strong>PHP</strong> provides a move_uploaded_file( ) function that moves the file only if it was an<br />

uploaded file.This is preferable to moving the file directly with a system-level<br />

290 | Chapter 12: Security<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

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

Saved successfully!

Ooh no, something went wrong!