Secure image upload with PHP?

狂风中的少年 提交于 2019-12-12 08:17:23

问题


I want to upload images to my server from browser window. However, the upload field will be visible for everyone, so I need to set up some restrictions. I've only found the w3schools file upload (and as of w3fools.com I don't trust it). I want the restrictions to be:

Maximum size 2,5M

Image types jpg, jpeg, png, gif

So here's the code that w3schools provides, but it won't actually save the file anywhere? I've modified it a bit to meet my needs.

<?php
$allowedExts = array("jpg", "jpeg", "gif", "png");
$extension = end(explode(".", $_FILES["file"]["name"]));
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/jpeg"))
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2500000)
&& in_array($extension, $allowedExts))
  {
  if ($_FILES["file"]["error"] > 0)
    {
    echo "Error: " . $_FILES["file"]["error"] . "<br />";
    }
  else
    {
    echo "Upload: " . $_FILES["file"]["name"] . "<br />";
    echo "Type: " . $_FILES["file"]["type"] . "<br />";
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
    echo "Stored in: " . $_FILES["file"]["tmp_name"];
    }
  }
else
  {
  echo "Invalid file";
  }
?>

And as I don't want my site to be hacked, I want a secure solution, any help on this?

Edit

The code doesn't even do anything. So how should I do it?


回答1:


You need to use php move_upload_file function and also I have made changes to your if statement here is the working and tested example:

<?php

if (isset($_REQUEST["submit"])) {

    $allowedExts = array("jpg", "jpeg", "gif", "png");
    $extension = end(explode(".", $_FILES["file"]["name"]));

    if ($_FILES["file"]["type"] == "image/gif" || $_FILES["file"]["type"] == "image/jpg" || $_FILES["file"]["type"] == "image/jpeg" || $_FILES["file"]["type"] == "image/png" && $_FILES["file"]["size"] < 2500000 && in_array($extension, $allowedExts)) {

      if ($_FILES["file"]["error"] > 0) {

        echo "Error: " . $_FILES["file"]["error"] . "<br />";

      }
      else {

        $fname = $_FILES["file"]["name"];
        move_uploaded_file($_FILES["file"]["tmp_name"], $fname);

        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Stored in: " . $fname;

      }

    }
    else {

      echo "Invalid file type";

    }

}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" name="submit" value="submit" />
</form>

You can also use getimagesize function as suggested by doing next thing:

$size = getimagesize("http://www.simplestudio.rs/060620121945.jpg");

$file_format = $size['mime'];

$file_format will be represented as for example "image/jpeg" so you can easily check for image types like this:

foreach($allowedExts as $allowed) {

$chk_types = strpos($file_format, $allowed);

if($chk_types > -1) {
$type_is_good = true;
break;
}

}



回答2:


Use : move_uploaded_file, See, Manual

And one more thing,

the $_FILES["file"]["type"] variable is not good to use as this can be changed by the browser settings.

Use getimagesize instead, See, Manual




回答3:


  1. $ratio2) { $thumb_w=$new_w; $thumb_h=$old_y/$ratio1; } else { $thumb_h=$new_h; $thumb_w=$old_x/$ratio2; }
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
    
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y);
    
                if(!strcmp("png",$ext))             imagepng($dst_img,$filename);       else            imagejpeg($dst_img,$filename); 
            imagegif($dst_img,$filename);
                imagedestroy($dst_img);         imagedestroy($src_img);   }  }  if(!function_exists('getExtension'))    {       function
    
    getExtension($str) { $i = strrpos($str,"."); if (!$i) { return ""; } $l = strlen($str) - $i; $ext = substr($str,$i+1,$l); return $ext; } }
    $image=$_FILES["$imagename"]['name'];   if($image)      {  
        $filename = stripslashes($_FILES["$imagename"]['name']); 
        $extension = getExtension($filename);       $extension =
    
    strtolower($extension); if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif") && ($extension != "bmp")) {
            $obj->set_flash("Unknown extension...!");           header("Location: $filename ");             exit;       }       else        {
    
            $size=getimagesize($_FILES["$imagename"]['tmp_name']);
            $sizekb=filesize($_FILES["$imagename"]['tmp_name']);
    
            if ($sizekb > MAX_SIZE*1024)
            {
                $obj->set_flash("You have exceeded the size limit...!");
                header("Location: $filename");
                exit;
            }
    
        $select_max = $obj->sql_query("select max($fieldname) as MaxID from  ".$tablename."");
                        if($action=="Add")          {
                $Max = $select_max[0]['MaxID'];
                $image_name = $Max + 1;
                $new_name = $image_name.".".$extension;//the new name will be containing the full path where will be stored (images folder)
                $$imagename = $new_name;//New Name of Image same as Image Field Name
                $thumbfilename = $new_name;
                $newname="$uploadpath/large/".$new_name;
    
                $copied = copy($_FILES["$imagename"]['tmp_name'], $newname);
                //we verify if the image has been uploaded, and print error instead
                if (!$copied) 
                { 
                    $obj->set_flash("Copy unsuccessfull...!");
                    header("Location: $filename");
                    exit;
                }
                else
                {
                    $thumb_name="$uploadpath/thumb/".$thumbfilename;
                    $thumb=make_thumb($newname,$thumb_name,$WIDTH,$HEIGHT);
                }           }           if($action=="Update")           {
    
                $new_name=$ID.".".$extension;
                $$imagename = $new_name;//New Name of Image same as Image Field Name
                $newname = "$uploadpath/large/".$new_name;
                $thumbfilename = $new_name;
                $copied = copy($_FILES["$imagename"]['tmp_name'], $newname);
    
                if (!$copied) 
                {
                    $obj->set_flash("Copy unsuccessfull...!");
                    header("Location: $filename");
                    exit;
                }
                else
                {
                    $thumb_name="$uploadpath/thumb/".$thumbfilename;
                    $thumb=make_thumb($newname,$thumb_name,$WIDTH,$HEIGHT);
                }           }       }   }       if($action=="Delete")   {       $SelectImage = $obj->sql_query("select $imagename from  $tablename where $fieldname
    
    = ".$$fieldname." "); $ThisImage = $SelectImage[0]["$imagename"]; unlink("$uploadpath/thumb/".$ThisImage); unlink("$uploadpath/large/".$ThisImage); } ?>
    1. List item



回答4:


<?php

          $file_name   = $_FILES['file']['name'];
          $file_size   = $_FILES['file']['size'];
          $file_tmp    = $_FILES['file']['tmp_name'];
          $file_type   = $_FILES['file']['type'];

          /* variable array for store errors */
          $errors   = [];                   


          /* Check if file already exists in location file save */
          $file_dir  = "uploads";
          /** if folder not exists, then create it **/
          if (!file_exists($file_dir)) {
            mkdir($file_dir, 0777, true);
          }

          $file_target = $file_dir . $file_name;
          if (file_exists($file_target)) {
            //$errors[] = "Sorry, <strong>{$file_name}</strong> already exists.";
          }


             /* Check file size */
          if ($file_size > 2500000) {
            $errors[] = "Sorry, <strong>{$file_name}</strong> is too large. It size is {$file_size} > 2500000 bytes";
          }


          /* Check current file formats with file secure */
          $file_secure  = array('jpg', 'jpeg', 'png', 'gif');                   
          $file_current = strtolower(pathinfo($file_name, PATHINFO_EXTENSION)); /* (end(explode('.', $file_name) */

          if (in_array($file_current, $file_secure) === false) {
            $errors[] = "Sorry, <strong>{$file_current}</strong> extension not allowed";            
          }


          /* Check if Errors exist, then not upload. Or if Errors NOT exist, then try upload */
          if (!empty($errors)) {                            

            /* display error */                 
            foreach ($errors as $keyError => $valueError) {
              echo "$keyError = $valueError <br />";
            }

            echo "<br />";
            echo "<strong>{$file_name}</strong> could not uploaded. <hr />";                            

          } else {

            if (move_uploaded_file($file_tmp, $file_target)) {

              echo "Upload: "    . $file_name . "<br />";
              echo "Type: "      . $file_type . "<br />";
              echo "Size: "      . ($file_size / 1024) . " Kb<br />";
              echo "Stored in: " . $file_tmp;

            } else {

              echo "Invalid file";

            }

          }

?>


来源:https://stackoverflow.com/questions/12617070/secure-image-upload-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!