简体   繁体   中英

How Can I Secure This PHP Upload Script

I've read the Secure PHP Upload Scripts thread but I'm having difficulty getting this known good script to accept changes. I want this script to only allow .jpeg, .png, and .gif files. Could someone advise me on how to modify this script to do so?

<?php
$result=0;
if (trim($_POST["action"]) == "Upload File") { //**** User Clicked the Upload File Button

   //*********** Execute the Following Code to Upload File *************
   $imagename = basename($_FILES['image_file']['name']);  // grab name of file 
   $result = @move_uploaded_file($_FILES['image_file']['tmp_name'], $imagename); // upload it 
   if ($result==1) echo("Successfully uploaded: <b>".$imagename."</b>"); // did it work?

} // end if
?>
<?php
if ($result==1) echo("<img src='".$imagename."'>"); // display the uploaded file
?>
$filename = $_FILES['image_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext !== 'jpg' && $ext !== 'png' && $ext !== 'gif') {echo 'error';}

is a very bad idea for validation.

echo '<pre>';
$filename = 'image.php\0.jpg';

$extension = pathinfo($filename, PATHINFO_EXTENSION);
var_dump($ext);

The var_dump displays jpg

And the php function move_uploaded_file is vulnerable with null bytes \\0. After the move_uploaded_file the server will create a image.php file..

If you want to stop the upload before it reaches your server, you can filter it with javascript. See this SO answer for more information: stackoverflow.com/questions/71944/… – Kevin Apr 26 at 22:13

Never never never never neverever put trust in client side validation...


Coding a safe upload is hard. Very hard.

You can't trust file extensions or mime type because clients can change this.

If you only want an upload for gif, jpeg or png you could take these steps. With png you can have trouble because of the encoding that can bypass some of these.

  1. Read the temp file by file_get_contents() .
  2. Run strip_tags() on it.
  3. Create new images with the GD library
  4. Serve the image by read() - Don't use include() or require()
  5. Disable php engine on that directory

For the sake of brevity, i'm not doing any error checking.. but you can evaluate the extension of a file like this:

$filename = $_FILES['image_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if($ext !== 'jpg' && $ext !== 'png' && $ext !== 'gif') {echo 'error';}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM