CodeIgniter Forums

Full Version: How to Check if a file has been selected for upload?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.

El Forum

I'm trying to get a form working which allows the option to upload a file...

However, choosing to upload a file is not a requirement of the form, so i how can check if the user has choosen a file for upload? As i need to execute some extra code if an upload if going to be needed.

I think i read somewhere that we can't check the post data for the file upload input as it doesn't exist in the same way that the usual data from input boxes does.

i.e - I can't go
if  ($this->input->post('userfile'))

El Forum

Uploaded file data is not available in the $_POST. If you do a print_r($_FILES) after a form has been submitted with NO upload, you'll see that $_FILES['error'] = 4 (I think, something along those lines at least).

So to check if a file has been uploaded you do something like if($_FILES['error'] !== 4) then file was uploaded. If the value is 4 then proceed as if no file was uploaded.

El Forum

Thanks Stef, thats working but i actually needed to use the follwoing to access the error
$_FILES['userfile']['error'] !==4

Would i be right in thinking that different numbers will related to different errors - if so do you know where i can find a reference of the error numbers?

Many Thanks

El Forum

Via Google "file upload error codes":

There are 8 different error codes.

Since PHP 4.2.0, PHP returns an appropriate error code along with the file array. The error code can be found in the error segment of the file array that is created during the file upload by PHP. In other words, the error might be found in $_FILES['userfile']['error'].


    Value: 0; There is no error, the file uploaded with success.

    Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.

    Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.

    Value: 3; The uploaded file was only partially uploaded.

    Value: 4; No file was uploaded.

    Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.

    Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.

    Value: 8; A PHP extension stopped the file upload. PHP does not provide a way to ascertain which extension caused the file upload to stop; examining the list of loaded extensions with phpinfo() may help. Introduced in PHP 5.2.0.

El Forum

cheers Stef