How To Detect File Uploading Errors

Q

How To Detect File Uploading Errors? - PHP Script Tips - Uploading Files to Web Servers

✍: FYIcenter.com

A

If there was a problem for a file upload request specified by the <INPUT TYPE=FILE NAME=fieldName...> tag, an error code will be available in $_FILES[$fieldName]['error']. Possible error code values are:

  • UPLOAD_ERR_OK (0) - There is no error, the file uploaded with success.
  • UPLOAD_ERR_INI_SIZE (1) - The uploaded file exceeds the upload_max_filesize directive in php.ini.
  • UPLOAD_ERR_FORM_SIZE (2) - The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
  • UPLOAD_ERR_PARTIAL (3) - The uploaded file was only partially uploaded.
  • UPLOAD_ERR_NO_FILE (4) - No file was uploaded.
  • UPLOAD_ERR_NO_TMP_DIR (5) - Missing a temporary folder.

Based on the error codes, you can have a better logic to process uploaded files more accurately, as shown in the following script:

<?php
  $file = '\fyicenter\images\fyicenter.logo';
  $error = $_FILES['fyicenter_logo']['error'];
  $tmp_name = $_FILES['fyicenter_logo']['tmp_name'];
  print("<pre>\n");
  if ($error==UPLOAD_ERR_OK) {
    move_uploaded_file($tmp_name, $file);
    print("File uploaded.\n");
  } else if ($error==UPLOAD_ERR_NO_FILE) {
    print("No files specified.\n");
  } else {
    print("Upload faield.\n");
  }
  print("</pre>\n");
?>

If you try this script with logo_upload.php and do not specify any files, you will get the "No files specified." message.

2007-04-19, 4945👍, 0💬