Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists in the upload file array

Tags:

forms

php

I got form at frontend to submit stuff, wherein I need to check if file exists on submit.

Please note that the form submits array of files. It is failing the all logics I have been trying. Please notice the upload[] on second line of html.

HTML

<form method="post" id="upload-form" action="" enctype="multipart/form-data" >
<input type="file" multiple="true" name="upload[]">
<input type="submit" name="upload_attachments" value="UPLOAD">
<form>

PHP

if(!file_exists($_FILES['upload']['tmp_name'].'/'.$FILES['upload']['name'])) {

   $upload_error = 'file is not set !'; 
   return; //stop further code execution 
   }else{

   //do further validation   

   }

The code above shows 'file is not set !' in both cases, that is when I hit submit button without uploading a file and when I select to upload a file and hit the submit button.

What is happening here, am I even doing it right?

Basically I want to return a 'File Empty' message when someone hits the submit button without selecting a file to upload, and stop the further code execution.

like image 721
gurung Avatar asked May 29 '14 09:05

gurung


2 Answers

$_FILES[<key>]['tmp_name'] - contains file path on server

$_FILES[<key>]['name'] - is just original file name

To address array of files file[] you need to fetch data by $_FILES[<key>][<property>][<id>]

try

if(!file_exists($_FILES['upload']['tmp_name'][0])) {

Manuals

http://www.php.net/manual/en/features.file-upload.php

http://www.php.net/manual/en/features.file-upload.multiple.php

like image 56
mleko Avatar answered Sep 23 '22 07:09

mleko


You are appending tmp_name and name. That is not needed. Just check uploaded file name like;

if(empty($_FILES['upload']['name'])) {

   $upload_error = 'file is not set !'; 
   return; //stop further code execution 
}else{

   //do further validation   

}

or you can check file existence like;

if(!file_exists($_FILES['upload']['tmp_name'][0])) {

   $upload_error = 'file is not set !'; 
   return; //stop further code execution 
}else{

   //do further validation   

}

Your multiple file array format is like below;

Array
(
    [name] => Array
        (
            [0] => foo.txt
            [1] => bar.txt
        )

    [type] => Array
        (
            [0] => text/plain
            [1] => text/plain
        )

    [tmp_name] => Array
        (
            [0] => /tmp/phpYzdqkD
            [1] => /tmp/phpeEwEWG
        )

    [error] => Array
        (
            [0] => 0
            [1] => 0
        )

    [size] => Array
        (
            [0] => 123
            [1] => 456
        )
)

You can refer here

like image 34
Hüseyin BABAL Avatar answered Sep 22 '22 07:09

Hüseyin BABAL