Check for empty files in http upload using PHP

Bad upload process could result in empty files and developers need to check for empty files before using them, because the PHP engine could give no error. For example, if a user typed a bad file name in the upload field and submitted the form, the PHP engine will take it as an empty file without raising any error.

<?php
  $file = '/tmp/w3img.gif';
  $error = $_FILES['w3img']['error'];
  $tmp_name = $_FILES['w3img']['tmp_name'];
  print("
\n");
  if ($error==UPLOAD_ERR_OK) {
    if ($_FILES['w3img']['size'] > 0) {
      move_uploaded_file($tmp_name, $file);
      print("File uploaded.\n");
    } else {
      print("Loaded file is empty.\n");
    }
  } else if ($error==UPLOAD_ERR_NO_FILE) {
    print("No files specified.\n");
  } else {
    print("Upload failed.\n");
  }
  print("
\n");
?>

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Filed Under: PHP File Handling

Tags:

RSSComments (0)

Trackback URL

Leave a Reply




If you want a picture to show with your comment, go get a Gravatar.