Accepting user uploads to our site requires both validation and security: validation to check that the file is correct (the right size and format) and security to ensure that nothing nefarious is being uploaded. So far in I’ve made a form and a basic PHP page that transfers the file; what we want now is to make that transfer conditional on the file passing several tests.

Turning back to the PHP for transferring the file, we’ll add two lines. These additions will not prevent the file from being uploaded, but they will give us a hint as to what we should inspect to see if we should do so:

<?php
	$upload_tmp_dir = "/tmp";
	$imageinfo = getimagesize($_FILES['upload']['tmp_name']);
	print_r($imageinfo);
	$uploadedfile = "images/{$_FILES['upload']['name']}";
	if (move_uploaded_file ($_FILES['upload']['tmp_name'], $uploadedfile )) {
		echo "File successfully uploaded";
	} else {
		echo "Failure to upload";
?>

Run the form you previously made, and take a look at what the receiving page now prints out.

getimagesize is actually a little bit of a misnormer; while the function does give us information about the image's dimensions, it also looks at the MIME type and other details. It is this information, along with the physical size of the file in bytes, that we want to check. Let's say you only wanted to accept JPEG and PNG images. To cover the bases, you could wrap the move_uploaded_file function with an if statement:

if ($imageinfo['mime'] == ("image/png" || "image/jpg" || "image/jpeg" || "image/pjpg")) { 
	$uploadedfile = "images/{$_FILES['upload']['name']}";
	if (move_uploaded_file ($_FILES['upload'] ['tmp_name'], $uploadedfile )) {
	echo "<p>File successfully uploaded>/p<";
		} else {
	echo "<p>Failure to upload>/p<";
}
} else { 
 	echo "<p>Your file was not accepted.>/p<";
}

If you wanted to add a check of the file size, the if condition could be altered to include:

if ($imageinfo['mime'] == ("image/png" || "image/jpg" || "image/jpeg" || "image/pjpg") && $imageinfo['size'] > 61440)

(Note that this file size limit is the same as the MAX_FILE_SIZE set in our original form.)

There are many more tests that we could do, but these two conditions would be enough to ensure that your site is receiving the kind of file that you want to accept while keeping basic security protocols in place.

Important note

One thing we have not done is check the uploaded file name, to see if it clashes with an existing file in the location where we are moving the file. If it does, PHP will not hesitate to overwrite the older file with the new one.