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 the 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 "Error without file" even if I do something. Any clue? Sorry I'm really new to PHP.

EDIT: I already tried to replace $ 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 the file?

+4
source share
3 answers

Use an array $_FILESand a constant 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, , ( ).

: empty() $_FILES['file_upoad'], , error , , empty() false.

+6

""

  /* check input 'submit' */        
  if (isset($_POST['submit'])) {
    print($_FILES);
  }

:

> Array (
>     [file_upload] => Array
>         (
>             [name] => 
>             [type] => 
>             [tmp_name] => 
>             [error] => 4
>             [size] => 0
>         )
> 
> )

[file_upload] [error] = 4, .
= 4, UPLOAD_ERR_NO_FILE.
, = 0.

isset, 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 with php 4.1.0. This variable stores information about downloaded files. Therefore you must encode

$fileupload = $_FILES['file_upload'];
if (isset($fileupload)) {
    print_r($_FILES);
} else {
    echo "Error no file selected";     
}
-2
source

All Articles