Right method to begin server side validation for file uploads

What is the right way to begin validation for data sent by a multipart/form form. I’ll be receiving a file and 1 text identifier from a hidden field.

I’m not asking how to check for file type and size and all else. I can do that :slight_smile: What I’m asking is: in a normal form I usually do this:

<?php

If ($_POST)
{

if (isset($_POST['myField]) && $_POST['myField'] == 1)
{
//Proceed with the rest
}else{
echo 'Error';
}
}
else
{
echo 'Some Error';
}

?>

What’s the best way to do it when it come to multipart/form data? How do u pros / experienced guys do it?

Thanks

It depends on the file type you are uploading and any restrictions you are imposing. Look up the following PHP methods for more information:

is_uploaded_file
move_uploaded_file
mime_content_type (if you only accept gif, you want to catch and fail on bmp right?)
getimagesize (to check upload size limits if using images)
filesize (if not an image)

Between these, and basic checks, you should be able to determine validity of your upload.

To check first off if the upload happened without incident check the error code is not 0.


<?php 
if($_FILES['userfile']['error'] > 0) { 
  // handle the error 
  // redirect or whatever
} 

// proceed with other checks, move file etc
?>

Upload error codes