PHP检查是否选择了要上传的文件 [英] PHP check if there is a file selected for upload
问题描述
我有此表格,我想检查用户是否选择了文件.
I have this form and I would like to check if the user has selected a file or not.
<form action="upload.php" method="POST" enctype="multipart/form-data" >
<select name="category">
<option value="cat1" name="cat1">Productfotografie</option>
<option value="cat2" name="cat2">Portretten</option>
<option value="cat3" name="cat3">Achitectuur</option>
</select>
<input type="file" name="file_upload">
<input type="submit" name="submit" value="Upload photo">
</form>
我编写了此PHP代码以对其进行测试
I wrote this PHP code to test it
if (empty($_POST) === false) {
$fileupload = $_POST['file_upload'];
if (empty($fileupload) === true) { //
echo "Error no file selected";
} else {
print_r($_FILES);
}
}
但是,即使我选择了某些内容,也会出现错误,未选择文件".有什么线索吗?对不起,我真的是PHP新手.
But I get the "Error no file selected" even if I DO select something. Any clue? I'm sorry I'm really new in PHP.
编辑:我已经尝试替换了$fileupload = $_FILES['file_upload']
,但它会显示一个空错误
I already tried replacing $fileupload = $_FILES['file_upload']
but it prints an empty error
(Array([file_upload] => Array([name] => [type] => [tmp_name] => [错误] => 4 [大小] => 0))))
(Array ( [file_upload] => Array ( [name] => [type] => [tmp_name] => [error] => 4 [size] => 0 ) ))
当我不输入文件时?
推荐答案
使用$_FILES
数组和UPLOAD_ERR_NO_FILE
常量:
if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) {
echo "Error no file selected";
} else {
print_r($_FILES);
}
您还可以检查UPLOAD_ERR_OK
,该文件表示文件是否已成功上传(存在且没有错误).
You can also check UPLOAD_ERR_OK
which indicates if the file was successfully uploaded (present and no errors).
注意:您不能在$_FILES['file_upoad']
数组上使用empty()
,因为即使没有文件上传,该数组仍将被填充并且设置了error
元素,这意味着empty()
将返回false
Note: you cannot use empty()
on the $_FILES['file_upoad']
array, because even if no file is uploaded, the array is still populated and the error
element is set, which means empty()
will return false
.
这篇关于PHP检查是否选择了要上传的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!