Skip to Content
Programming PHP
book

Programming PHP

by Rasmus Lerdorf, Kevin Tatroe
March 2002
Intermediate to advanced
528 pages
21h 29m
English
O'Reilly Media, Inc.
Content preview from Programming PHP

File Uploads

File uploads combine the two dangers we’ve seen so far: user-modifiable data and the filesystem. While PHP 4 itself is secure in how it handles uploaded files, there are several potential traps for unwary programmers.

Distrust Browser-Supplied Filenames

Be careful using the filename sent by the browser. If possible, do not use this as the name of the file on your filesystem. It’s easy to make the browser send a file identified as /etc/passwd or /home/rasmus/.forward. You can use the browser-supplied name for all user interaction, but generate a unique name yourself to actually call the file. For example:

$browser_name = $_FILES['image']['name'];
$temp_name = $_FILES['image']['tmp_name'];
echo "Thanks for sending me $browser_name.";

$counter++; // persistent variable
$my_name = "image_$counter";
if (is_uploaded_file($temp_name)) {
  move_uploaded_file($temp_name, "/web/images/$my_name");
} else {
  die("There was a problem processing the file.");
}

Beware of Filling Your Filesystem

Another trap is the size of uploaded files. Although you can tell the browser the maximum size of file to upload, this is only a recommendation and it cannot ensure that your script won’t be handed a file of a larger size. The danger is that an attacker will try a denial of service attack by sending you several large files in one request and filling up the filesystem in which PHP stores the decoded files.

Set the post_max_size configuration option in php.ini to the maximum size (in bytes) ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Programming PHP, 3rd Edition

Programming PHP, 3rd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Programming PHP, 2nd Edition

Programming PHP, 2nd Edition

Rasmus Lerdorf, Kevin Tatroe, Peter MacIntyre
Clean Code in PHP

Clean Code in PHP

Carsten Windler, Alexandre Daubois

Publisher Resources

ISBN: 1565926102Supplemental ContentCatalog PageErrata