PHP检查上传的文件是否为图片

4

我想创建用户头像。我只是想确保它是安全的。检查文件是否为实际图像而不是其他任何东西的最佳方法是什么。

我已经尝试过这个:

$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";

    } else {
        echo "File is not an image.";
    }

尽管这种方法在某些图像上看似有效,但其他像照片一样的图像则可能导致失败。我用手机拍摄的照片似乎会显示“文件不是图像”,而其他照片则会显示图像。
我也一直在检查文件格式。
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";

}

1
你有 $imageFileType=$_FILES["fileToUpload"]["type"] - Hikmat Sijapati
3个回答

2

0

您可以直接使用getimagesize(),对于非图片文件,它将返回零值。


每当我上传某些照片时,它就会显示一个错误。 - Bryce Harrison
使用 $img = @imagecreatefromstring (@file_get_contents($path_to_img)); 如果结果为 false,则您上传的文件不是图像。如果为 true,则成功了! - user4395445
抱歉再次提到getimagesize(),你面临的问题是由于图像的元标记。因为大多数图像包含隐藏的元标记,所以你的结果不准确,但是imagecreatefromstring可以解决这个问题。 - user4395445
6
注意:此函数期望文件名为有效的图像文件。如果提供了非图像文件,则可能会错误地将其识别为图像,并且函数将成功返回,但数组可能包含无意义的值。不要使用getimagesize()来检查给定的文件是否为有效图像。而应该使用专门的解决方案,如Fileinfo扩展。 - Dennis Heiden

-1

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>


1
因为复制粘贴W3Schools页面而被踩。这是大多数人在尝试解决问题时找到的代码... - The One True Colter

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接