PHP File Upload – Error Codes & Sample Scripts

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.

Error Code Description
UPLOAD_ERR_OK Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR Value: 6; Missing a temporary folder. Introduced in PHP 4.3.10 and PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION 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.

 

Sample Implementation of PHP File Upload :

<?php

function get_file_upload_error_message($error_code) {
switch ($error_code) {
case UPLOAD_ERR_INI_SIZE:
return ‘The uploaded file exceeds the upload_max_filesize directive in php.ini’;
case UPLOAD_ERR_FORM_SIZE:
return ‘The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form’;
case UPLOAD_ERR_PARTIAL:
return ‘The uploaded file was only partially uploaded’;
case UPLOAD_ERR_NO_FILE:
return ‘No file was uploaded’;
case UPLOAD_ERR_NO_TMP_DIR:
return ‘Missing a temporary folder’;
case UPLOAD_ERR_CANT_WRITE:
return ‘Failed to write file to disk’;
case UPLOAD_ERR_EXTENSION:
return ‘File upload stopped by extension’;
default:
return ‘Unknown upload error’;
}
}

if ($_FILES[‘file’][‘error’] === UPLOAD_ERR_OK)
else
$error_message = get_file_upload_error_message($_FILES[‘file’][‘error’]);
echo $error_message;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *