File Upload Security

This sections will contains code regarding different PHP & MySQL features and contains help about php/mysql issues.

File Upload Security

Postby Web Guru on March 25th, 2008, 4:33 am

Take this standard file upload form:
Code: Select all
<FORM ENCTYPE="multipart/form-data" ACTION="upload.php" METHOD=POST>
<INPUT TYPE="hidden" name="MAX_FILE_SIZE" value="100000">
Send this file: <INPUT NAME="myfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File">
</FORM>

The correct way to put the uploaded file in the right place:
Code: Select all
<?php
/* Not under DOCUMENT_ROOT */
$destination = "/some/path/$myfile_name";
move_uploaded_file($myfile, $destination);
?>

If you are uploading files to be placed somewhere under the DOCUMENT_ROOT then you need to
be very paranoid in checking what you are putting there. For example, you wouldn't want to let people upload arbitrary PHP scripts that they can then browse to in order to execute them. Here we get paranoid about checking that only image files can be uploaded. We even look at the contents of the file and ensure that the file extension matches the content.
Code: Select all
<?php
$type = $HTTP_POST_FILES['myfile']['type'];
$file = $HTTP_POST_FILES['myfile']['tmp_name'];
$name = $HTTP_POST_FILES['myfile']['name'];
$types = array(0,'.gif','.jpg','.png','.swf');
list(,,$type) = getimagesize($file);
if($type) {
$name = substr($name,0,strrpos($str,'.'));
$name .= $types[$type];
}
move_uploaded_file($myfile, "$DOCUMENT_ROOT/images/$name");
?>
User avatar
Web Guru
 
Posts: 75
Joined: March 24th, 2008, 7:59 am
Location: Lahore, Pakistan

Return to PHP / MySQL / XML

Who is online

Users browsing this forum: No registered users and 0 guests

cron