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>
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);
}
}
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.
EDIT: I already tried replacing $fileupload = $_FILES['file_upload']
but it prints an empty error
(Array ( [file_upload] => Array ( [name] => [type] => [tmp_name] =>
[error] => 4 [size] => 0 ) ))
when I do NOT enter a file?
5
Use the $_FILES
array and the UPLOAD_ERR_NO_FILE
constant:
if(!isset($_FILES['file_upload']) || $_FILES['file_upload']['error'] == UPLOAD_ERR_NO_FILE) {
echo "Error no file selected";
} else {
print_r($_FILES);
}
You can also check UPLOAD_ERR_OK
which indicates if the file was successfully uploaded (present and no errors).
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
.
3
First, click submit without choose file
/* check input 'submit' */
if (isset($_POST['submit'])) {
print($_FILES);
}
Result:
> Array ( > [file_upload] => Array > ( > [name] => > [type] => > [tmp_name] => > [error] => 4 > [size] => 0 > ) > > )
There are array of [file_upload][error] = 4, NOT null or whitespace.
Code value = 4 , meaning UPLOAD_ERR_NO_FILE.
If success and no error, code value = 0.
Check here
So use function isset, not empty
/* check input submit */
if (isset($_POST['submit'])) {
/* check input file_upload on error */
if (isset($_FILES['file_upload']['error'])) {
/* check code error = 4 for validate 'no file' */
if ($_FILES['file_upload']['error'] == 4) {
echo "Please select an image file ..";
}
}
}
0
According to http://www.php.net there is $_FILES available since php 4.1.0. This variable keeps information about uploaded files. So you should code
$fileupload = $_FILES['file_upload'];
if (isset($fileupload)) {
print_r($_FILES);
} else {
echo "Error no file selected";
}
2