PHP Easy file uploading vs. ASP file uploading

I have to admit, uploading a file in PHP is so much easier than doing the same thing in ASP.

With ASP, I used a 3rd-party component (DLL) SA-FileUpload to do my file uploads.

With PHP, file upload capability is already built-in. The file information can easily be accessed by the following variables.

echo 'filename: ' . $_FILES['uploadfile']['name'];
echo "<br>";
echo 'file type: ' . $_FILES['uploadfile']['type'];
echo "<br>";
echo 'size: ' . $_FILES['uploadfile']['size'];
echo "<br>";
echo 'tmp_name: '. $_FILES['uploadfile']['tmp_name'];
echo "<br>";
echo "error code: " . $_FILES['uploadfile']['error'];

The uploaded file is stored in a temporary location with a temporary filename. Then you do your file validation, and if everything is OK, you need to move the temporary file to it’s final destination and filename.

// this is our upload directory
$uploaddir = 'uploads/';

// build fullpathname ,i.e. uploaddir + filename
$uploadfile = $uploaddir . basename($_FILES['uploadfile']['name']);

… do your file validation here, check file extension, size, etc…

if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
$errmessage ="file upload failed";
echo $errmessage;
} // end if move

Easy peasy!

Any failure in the file upload process will be registered in this variable.

$_FILES[‘uploadfile’][‘error’]

Possible values are (say you’re using a Switch statement):

case UPLOAD_ERR_INI_SIZE:    // 1
   return 'ERR: The uploaded file exceeds the upload_max_filesize directive in php.ini';
case UPLOAD_ERR_FORM_SIZE:    // 2
   return 'ERR: The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
case UPLOAD_ERR_PARTIAL:    // 3
   return 'ERR: The uploaded file was only partially uploaded';
case UPLOAD_ERR_NO_FILE:    // 4
   return 'ERR: No file was uploaded';
case UPLOAD_ERR_NO_TMP_DIR:    // 6
   return 'ERR: Missing a temporary folder';
case UPLOAD_ERR_CANT_WRITE:    // 7
   return 'ERR: Failed to write file to disk';
case UPLOAD_ERR_EXTENSION:    // 8
   return 'ERR: File upload stopped by extension';
This entry was posted in Uncategorized and tagged , , . Bookmark the permalink.