【发布时间】:2011-05-09 04:21:34
【问题描述】:
我正在编写一个脚本来将图像上传到我的应用程序。以下安全步骤是否足以使应用程序在脚本方面安全?
- 使用 .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";
}
欢迎任何新的提示:)
【问题讨论】:
-
我会删除以下规则:如果文件名包含字符串“php”,则不允许上传。不需要,因为您正在重命名文件。
-
你可以从github下载Secure Image upload。它是目前最安全的 PHP 脚本。它也支持图像调整大小/裁剪。
-
@Alez 快速浏览该类,我能看到的唯一安全性是扩展检查。请,请说不是这样!
-
@Fricker 不是这样。凭什么?
pathinfo(, PATHINFO_EXTENSION)是一种获得最准确文件扩展名的非常可靠的方法,实际上没有比这更可靠的了。阅读上面写着"note" -
@Alez ofc & btw 我喜欢 Luke 3:11 的许可证 :)