使用PHP保护图像上传?

时间:2012-09-27 08:26:18

标签: php file-upload image-upload

我想从浏览器窗口将图像上传到我的服务器。但是,每个人都可以看到上传字段,因此我需要设置一些限制。我只发现w3schools文件上传(从w3fools.com开始我不信任它)。我希望限制为:

最大尺寸为2,5M

图片类型jpg,jpeg,png,gif

所以这是w3schools提供的代码,但它实际上不会将文件保存在任何地方?我已经修改了一下以满足我的需求。

<?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";
  }
?>

由于我不希望我的网站被黑客攻击,我想要一个安全的解决方案,对此有任何帮助吗?

修改

代码甚至没有做任何事情。那我该怎么做呢?

4 个答案:

答案 0 :(得分:3)

你需要使用php move_upload_file函数,并且我已经对你的if语句进行了更改,这里是工作和测试的例子:

<?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>

你也可以按照下一步的建议使用getimagesize功能:

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

$file_format = $size['mime'];

$ file_format将表示为例如“image / jpeg”,因此您可以轻松检查这样的图像类型:

foreach($allowedExts as $allowed) {

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

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

}

答案 1 :(得分:1)

使用:move_uploaded_file,参见Manual

还有一件事,

$_FILES["file"]["type"]变量不适合使用,因为浏览器设置可以更改它。

请改用getimagesize,参见Manual

答案 2 :(得分:0)

  1. $ ratio2){$ thumb_w = $ new_w;             $ thumb_h = $ old_y / $比1; } else {$ thumb_h = $ new_h;             $ thumb_w = $ old_x / $比* 2; }
        $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);          返回$ ext; }}
    $image=$_FILES["$imagename"]['name'];   if($image)      {  
        $filename = stripslashes($_FILES["$imagename"]['name']); 
        $extension = getExtension($filename);       $extension =
    
    用strtolower($扩展); if(($ extension!=“jpg”)&amp;&amp;($ extension !=“jpeg”)&amp;&amp; ($ extension!=“png”)&amp;&amp; ($ extension!=“gif”)&amp;&amp; ($ 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);         取消链接(“$ uploadpath /大/".$ ThisImage); }?&gt;
    1. 列表项

答案 3 :(得分:0)

<?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";

            }

          }

?>