PHP检查上传的文件是否是图像

时间:2017-01-26 04:08:47

标签: php image upload

我正在尝试创建用户头像。我只是想确保它的安全。检查文件是否是实际图像的最佳方法是什么,而不是其他任何内容。

我试过这个

$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.";

}

3 个答案:

答案 0 :(得分:1)

您可以使用php5功能

mime_content_type(string $ filename)

Php doc here:https://stackoverflow.com/a/39353961/4836759

这将返回,例如,“image / jpg”。解析结果,瞧!这样您就不必经历所有不同的类型。

答案 1 :(得分:0)

您可以直接使用manual,并且对于非图像的文件,它将返回零值。

答案 2 :(得分:0)

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