Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP check if there is a file selected for upload [duplicate]

Tags:

post

php

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?

like image 766
Mae Avatar asked Oct 17 '14 19:10

Mae


1 Answers

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.

like image 122
MrCode Avatar answered Nov 08 '22 10:11

MrCode