【问题标题】:How to catch an error for a file name error? [duplicate]如何捕获文件名错误的错误? [复制]
【发布时间】:2019-04-18 21:40:25
【问题描述】:

我正在为学校制作 Instagram 克隆,我目前正在开发“更新个人资料”功能,每当我尝试更新个人资料图片时,它就像一个魅力,但每当我不更新个人资料图片但我只是更新描述或用户名我收到以下错误。

“getimagesize(): 文件名不能为空”

当我不上传新的个人资料图片时,捕获此错误的最佳方法是什么?

我尝试了一种“try catch”方法,但它似乎不起作用。 (可能我以错误的方式实现它

    if(isset($_FILES["file"])){
        if(getimagesize($_FILES["file"]["tmp_name"]) !== false){
            $target_dir = "uploads/";
            $extention = explode(".", $_FILES["file"]["name"]);

            $i = count($extention) - 1;
            $target_file = $target_dir . basename($_FILES["file"]["tmp_name"] . "." . $extention[$i]);

            if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
                // File has been moved to Uploads/[temp_name].[extention]
                $user->setImage($target_file);
                $a["image"] = $target_file;
            } else {
                // The file did not move to the destonation folder
            }
        }
    }

当我不上传新图片而只是尝试更新我的用户名或描述时,我希望这不会向我返回错误。

【问题讨论】:

  • 如果您也在查看您的通知,您将收到未定义的索引通知。在尝试使用它们之前检查 $_FILES 是否存在并具有适当的密钥。

标签: php try-catch


【解决方案1】:

您可以检查错误索引是否为零(UPLOAD_ERR_OK),如果错误不为零导致没有文件上传,UPLOAD_ERR_NO_FILE 将在那里

如果你只是想检查上传是否顺利,你可以写:

if ($_FILES['file']['error'] == UPLOAD_ERR_OK) {
    // file is good (and not an error)
}

如果你想检查文件没有上传

if ($_FILES['file']['error'] == UPLOAD_ERR_NO_FILE) {
    // file is empty, no upload
}

查看PHP Reference了解更多信息!

【讨论】:

    猜你喜欢
    • 2012-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-16
    • 2015-05-24
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多