【问题标题】:Image uploading error in PHPPHP中的图像上传错误
【发布时间】:2017-03-10 08:44:01
【问题描述】:
<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():文件名不能为空 C:\wamp64\www\company\test\upload.php 第 8 行

文件不是图像。

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

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

是空的,但是,

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

不为空。

【问题讨论】:

标签: php image-uploading getimagesize


【解决方案1】:
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;
}

【讨论】:

  • 我根据你的回答做了.. 事情是 $_FILES['fileToUpload']['tmp_name'] 是空的,但 $_FILES['fileToUpload']['name'] 不是空的。为什么会这样??
【解决方案2】:

您需要使用!empty 检查$_FILES 是否为空

if(isset($_POST["submit"]) && !empty($_FILES["fileToUpload"]) {
     // do your stuff
}

或者使用isset检查密钥是否存在而不是null

if (isset($_POST['submit'], $_FILES['fileToUpload'])) {
    // do your stuff
}

【讨论】:

猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 2023-03-17
  • 2021-09-07
  • 1970-01-01
  • 2015-01-07
  • 1970-01-01
  • 1970-01-01
  • 2016-03-08
相关资源
最近更新 更多