PHP中的图像上传错误

时间:2017-03-10 08:44:02

标签: php image-uploading getimagesize

<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>

以上是我的HTML代码。以下是我上传的PHP代码:

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

上传图片时,会返回以下内容:

  

警告:getimagesize():文件名不能为空   第8行的C:\ wamp64 \ www \ company \ test \ upload.php

文件不是图片。

代码有什么问题吗? 我使用的是PHP v5.6.16,请帮助我。

$_FILES["fileToUpload"]["tmp_name"]);

是空的,但是,

$_FILES["fileToUpload"]["name"]);

不是空的。

2 个答案:

答案 0 :(得分:0)

if(isset($_POST["submit"]) && isset($_FILES['fileToUpload'])) {
    $file_temp = $_FILES['fileToUpload']['tmp_name'];   
    $info = getimagesize($file_temp);
    if($info !== false) {
       echo "File is an image - " . $info["mime"] . ".";
       $uploadOk = 1;
    } else {
       echo "File is not an image.";
       $uploadOk = 0;
    }
} 
else if(isset($_POST["submit"]) && !isset($_FILES['fileToUpload'])) {
    print "Form was submitted but file wasn't send";
    exit;
}
else {
    print "Form wasn't submitted!";
    exit;
}

答案 1 :(得分:0)

您需要使用!empty

检查$_FILES是否为空
if(isset($_POST["submit"]) && !empty($_FILES["fileToUpload"]) {
     // do your stuff
}

或者仅使用isset

检查密钥是否存在而不是null
if (isset($_POST['submit'], $_FILES['fileToUpload'])) {
    // do your stuff
}