Validate an uploaded image in PHP

This is a quick copy and past, but you should get the idea. This script validates the form field “photo” file being upload is a valid photo.

	// Validate Photo
	if(!empty($_FILES['photo'])) { // Photo uploaded.
		if($_FILES['photo']['error'] != UPLOAD_ERR_OK) {
			$errors['photo'] = 'Server encountered an error while attempting to upload your Photo.';
		} else if(!is_uploaded_file($_FILES['photo']['tmp_name'])) { // File specified is local file system, not actually uploaded. BAD.
			$errors['photo'] = 'Photo specified is not valid.';
		} else { // Check if the image is valid by loading it into memory as an image.
			$image_info = @getimagesize($_FILES['photo']['tmp_name']); // Grabs the dimensions and type of image. May throw an error if not an image, not yet tested.
			$image_type = $image_info[2]; // Grab the image type.
			$image_function = False;
			if($image_type == IMAGETYPE_JPEG) {
				$image_function = 'jpeg';
			} else if($image_type == IMAGETYPE_PNG) {
				$image_function = 'png';
			} else if($image_type == IMAGETYPE_GIF) {
				$image_function = 'gif';
			} else if($image_type == IMAGETYPE_BMP) {
				$image_function = 'bmp';
			} else {
				$errors['photo'] = 'Photo uploaded does not appear to be a valid PNG, BMP, GIF or JPEG.';
			}
			if($image_function != False) { // Attempt to load the image into memory.
				$image_function = 'imagecreatefrom' . $image_function;
				$image = @$image_function($_FILES['photo']['tmp_name']); // Load the image into memory. May throw an error, su supress.
				if($image == False) { // If false, it means it was unable to load the image into memory.
					$errors['photo'] = 'Photo uploaded appears to be corrupt, unable to upload.';
				}
			}
			unset($image_info, $image_type, $image_function, $image); // Free no longer relavent memory.
		}
	}

Leave a Reply