PHP图片上传安全检查清单 [英] PHP image upload security check list

查看:23
本文介绍了PHP图片上传安全检查清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来将图像上传到我的应用程序.以下安全步骤是否足以从脚本端确保应用程序安全?

I am programming a script to upload images to my application. Are the following security steps enough to make the application safe from the script side?

  • 使用 .httaccess 禁止 PHP 在上传文件夹内运行.
  • 如果文件名包含字符串php",则不允许上传.
  • 仅允许扩展名:jpg、jpeg、gif 和 png.
  • 仅允许图像文件类型.
  • 禁止使用两种文件类型的图像.
  • 更改图像名称.
  • 上传到子目录而不是根目录.

这是我的脚本:

 $filename=$_FILES['my_files']['name'];
 $filetype=$_FILES['my_files']['type'];
 $filename = strtolower($filename);
 $filetype = strtolower($filetype);

 //check if contain php and kill it 
 $pos = strpos($filename,'php');
 if(!($pos === false)) {
  die('error');
 }




 //get the file ext

 $file_ext = strrchr($filename, '.');


 //check if its allowed or not
 $whitelist = array(".jpg",".jpeg",".gif",".png"); 
 if (!(in_array($file_ext, $whitelist))) {
    die('not allowed extension,please upload images only');
 }


 //check upload type
 $pos = strpos($filetype,'image');
 if($pos === false) {
  die('error 1');
 }
 $imageinfo = getimagesize($_FILES['my_files']['tmp_name']);
 if($imageinfo['mime'] != 'image/gif' && $imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime']      != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
   die('error 2');
 }
//check double file type (image with comment)
if(substr_count($filetype, '/')>1){
die('error 3')
}

 // upload to upload direcory 
 $uploaddir = 'upload/'.date("Y-m-d").'/' ;

if (file_exists($uploaddir)) {  
} else {  
    mkdir( $uploaddir, 0777);  
}  
  //change the image name
 $uploadfile = $uploaddir . md5(basename($_FILES['my_files']['name'])).$file_ext;



  if (move_uploaded_file($_FILES['my_files']['tmp_name'], $uploadfile)) {
 echo "<img id="upload_id" src="".$uploadfile.""><br />";
  } else {
   echo "error";
  }

欢迎任何新提示:)

推荐答案

使用 GD(或 Imagick)重新处理图像并保存处理后的图像.所有其他的对于黑客来说都只是有趣无聊.

Re-process the image using GD (or Imagick) and save the processed image. All others are just fun boring for hackers.

正如 rr 所指出的,使用 move_uploaded_file() 进行任何上传.

And as rr pointed out, use move_uploaded_file() for any upload.

后期顺便说一下,您可能希望对上传文件夹进行严格限制.这些地方是发生许多漏洞的黑暗角落之一.这适用于任何类型的上传和任何编程语言/服务器.检查 https://www.owasp.org/index.php/Unrestricted_File_Upload

Late By the way, you'd want to be very restrictive about your upload folder. Those places are one of the dark corners where many exploits happen. This is valid for any type of upload and any programming language/server. Check https://www.owasp.org/index.php/Unrestricted_File_Upload

这篇关于PHP图片上传安全检查清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆