PHP 安全图像上传 - 附加代码?

标签 php mysql image

这是我将图像文件上传到 php/mysql 服务器的代码。我读过类似的帖子和教程,但大多数人都说它们不完整。

这是否足以确保安全,或者还缺少什么?

if(isset($_FILES["file"]) && $_FILES["file"]['error'] == 0)
{
$file = $_FILES["file"];

    $file = $_FILES["file"]['name'];
    $file_type = $_FILES["file"]['type'];
    $file = strtolower($file);
    $file_type = strtolower($file_type);

    if(is_array($_FILES["file"]['error'])){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('Erro: Only one file accepted');
    }

    $max_file_size = 2097152;
    if($_FILES['file']['size'] >= $max_file_size || $_FILES['file']['size'] == 0){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('Erro: file size exceeded (2mb)');
    }

    /* check if contain php */
    $pos = strpos($file, 'php');
    if(!($pos === false)) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('Error: image has php script');
    }

/* finfo */ 
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($_FILES['file']['tmp_name']);
$allowed2 = array('jpg'=>'image/jpeg', 'png'=>'image/png', 'jpeg'=>'image/jpeg');
$ext = array_search($mime, $allowed2, true);

    if(false === $ext){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('FileInfo: Extension not allowed');     
    }

    /* get file extension */
    $file_ext = strrchr($file, '.');

    /* check if it is allowed */
    $allowed = array(".jpg",".jpeg",".png");
    if (!(in_array($file_ext, $allowed))) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('Extension not allowed');
    }

    /* check upload type */
    $pos = strpos($file_type,'image');
    if($pos === false) {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('error 1: Mime type not valid');
    }

    $imageinfo = getimagesize($_FILES['file']['tmp_name']);
    if($imageinfo['mime'] != 'image/jpeg'&& $imageinfo['mime'] != 'image/jpg'&& $imageinfo['mime'] != 'image/png') {
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
    die('error 2: size mime type not valid');
    }

    //check double file type (image with comment)
    if(substr_count($file_type, '/')>1){
        echo '<a href="cad_p.php">Try again</a>';
        echo "<br/>";
        echo "<br/>";
        die('error 3: double type');
    }

    /* upload to upload direcory */ 
    $uploaddir = 'up_files/';

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

if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "";
} else {
    echo "Error moving image file";
    echo '<a href="cad_p.php">Try again</a>';
}

$name = $_POST['name'];

if ($insert_stmt = $mysqli->prepare("INSERT INTO products (name, file) VALUES (?, ?)")) {$insert_stmt->bind_param('ss', $name, $uploadfile);

if (! $insert_stmt->execute()) {
    echo '<div class="register_success">';
    echo "Could not insert...";
    echo '</div>';
}else{
    echo '<div class="register_success">';
    echo "Product Insert success...";
    echo '</div>'; 
}

}
}
else
{
echo '<a href="cad_p.php">Tente novamente</a>';
echo "<br/>";   
echo "<br/>";   
die('No image file selected');  
}

最佳答案

阅读 PHP 手册中的评论后,我从一个名为 sparticvs 的用户那里找到了这个:

"A note of security: Don't ever trust $_FILES["image"]["type"]. It takes whatever is sent from the browser, so don't trust this for the image type. I recommend using finfo_open (http://www.php.net/manual/en/function.finfo-open.php) to verify the MIME type of a file. It will parse the MAGIC in the file and return it's type...this can be trusted (you can also use the "file" program on Unix, but I would refrain from ever making a System call with your PHP code...that's just asking for problems)."

转到此处并向下滚动以查看他的评论: http://php.net/manual/en/reserved.variables.files.php

如果您打算使用该解决方案,那么这里有一些建议:

使用 strip_tag() 这是在有人以某种方式设法做到的情况下 将一些 HTML 或 PHP 标记添加到您的代码中。 在这里阅读更多:http://php.net/manual/en/function.strip-tags.php

$name = $_POST['name'];这看起来很危险。你根本没有做任何检查。 我会再次推荐 strip_tags 并进行类型验证。

编辑: 我会将老师的笔记添加到这个答案中:

  • 使用 getimagesize() 确保它不是假文件,这将 失败时返回 false。 (或类似的东西)限制文件 大小。
  • 始终检查扩展程序并只允许您想要的扩展程序。
  • 更改文件名或清除名称使用 strip_tags/html实体。
  • 永远不要将文件直接保存在数据库中。
  • 如果文件名中有空格,请正确编码。

关于PHP 安全图像上传 - 附加代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32338352/

相关文章:

php 将 Excel 工作表导入 mysql cakephp 1.3

php - 您如何解析 MWS GetMatchingProduct 中的关系?

php - 套接字连接是否会优于 Intarvaled 数据库扫描和请求?

mysql - 如何选择具有相同商品 sku 和数量的订单?

python - 如何使用 python 在图像上绘制具有不同笔触和填充颜色的文本?

php - 通过 php/shell 脚本在 linux 中创建一个文件?

mysql - 检查每行的 id 是否在另一个表中作为 id 存在

mysql - INNER JOIN 表自身

html - 如何使用 Bootstrap 使图像响应?

html - 如何使用 css 在用户定义的框中包含文本?