如何检查 $_FILE 是否在 php 中设置?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5849670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:40:47  来源:igfitidea点击:

how to check if a $_FILE is set in php?

phpfile

提问by Nicolas de Fontenay

I've created a form with 3 <input type="file"/>

我创建了一个包含 3 的表单 <input type="file"/>

I see that I get an array with array(name=>"").

我看到我得到了一个数组array(name=>"")

So I check if ($_FILE["myfilename"]["name"]=="")instead.

所以我if ($_FILE["myfilename"]["name"]=="")改为检查。

This works but it seems rather unusual to me.

这有效,但对我来说似乎很不寻常。

I was wondering if there was a better way to check if a file input is set or not?

我想知道是否有更好的方法来检查是否设置了文件输入?

回答by Pekka

There is: is_uploaded_file(). When dealing with uploaded files, you should always use it (and its cousin move_uploaded_file()) for security reasons.

有:is_uploaded_file()。在处理上传的文件时,move_uploaded_file()出于安全原因,您应该始终使用它(及其表亲)。

回答by Shakti Singh

You can use emptyto check if a variable is blank or not but Pekka's solution is best in this way

您可以使用empty检查变量是否为空,但 Pekka 的解决方案最好以这种方式

if (empty($_FILES["myfilename"]["name"]))

If you are checking that if a variable is set you can use issetfunction

如果您正在检查是否设置了变量,则可以使用isset函数

回答by Ciaran McNulty

The best way, assuming you're using a recent PHP (4.2+), is to check that:

假设您使用的是最新的 PHP (4.2+),最好的方法是检查:

$_FILE['myfilename']['error'] === UPLOAD_ERR_OK

If this is true the upload worked, you can see the list of other possible values here

如果这是真的上传成功,您可以在此处查看其他可能值的列表

回答by Osahady

You can try this:

你可以试试这个:

if($_FILES['myfilename']['size'] > 0 ) {

}
else{
       echo 'File is not uploaded . . .';
}

回答by Manish Negi

Try this:

尝试这个:

if($_FILES["uploadImg"]['name'][0] != ''){
    //echo 'file attached';
}else{
    //echo 'no file attached';
}

This works for me...

这对我有用...