Script 11.2 Upload a File

Allow users to upload images to a folder on the server.

Output
Select a GIF, JPEG/JPG or PNG image of 512KB or smaller to be uploaded:

Source
<?php # Script 11.2 - upload_image.php

// Check if the form has been submitted:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {

	// Check for an uploaded file:
	if (isset($_FILES['upload']) && $_FILES['upload']['error'] == 0) {
		// Validate the type. Should be JPEG/JPG, PNG or GIF.
		$tempName = $_FILES['upload']['tmp_name'];
		$fileName = $_FILES['upload']['name'];
		$type =  exif_imagetype($tempName);
		$allowedFormats = array('1','2','3'); //accepts gif, jpg/jpeg, png
		
		
		if (in_array($type, $allowedFormats)) {
			// Move the file over.
			if (move_uploaded_file ($tempName, UPLOAD_DIR."/{$fileName}")) {
				createThumbnail($fileName,$type);
				$image_size = getimagesize(UPLOAD_DIR."/$fileName");
				$thumbnail = getThumbnail($fileName);
				echo "<div class=\"message\">Thank you. Your file has been uploaded!<br /><a title=\"view uploaded image\" href=\"javascript:create_window('$fileName',$image_size[0],$image_size[1])\">".$thumbnail."</a></div>";
			} // End of move... IF.
			
		} else { // Invalid type.
			echo '<p class="error">Image not uploaded. Format must be JPG/JPEG, GIF or PNG.</p>';
		}

	} // End of isset($_FILES['upload']) IF.
	
	// Check for an error:
	if ($_FILES['upload']['error'] > 0) {
		echo '<p class="error">The file could not be uploaded.<br />';
	
		// Print a message based upon the error.
		switch ($_FILES['upload']['error']) {
			case 1:
				print 'The file exceeds the upload_max_filesize setting in php.ini.';
				break;
			case 2:
				print 'The file exceeds the MAX_FILE_SIZE setting in the HTML form.';
				break;
			case 3:
				print 'The file was only partially uploaded.';
				break;
			case 4:
				print 'No file was uploaded.';
				break;
			case 6:
				print 'No temporary folder was available.';
				break;
			case 7:
				print 'Unable to write to the disk.';
				break;
			case 8:
				print 'File upload stopped.';
				break;
			default:
				print 'A system error occurred.';
				break;
		} // End of switch.
		
		print '</p>';
	
	} // End of error IF.
	
	// Delete the file if it still exists:
	if (file_exists ($_FILES['upload']['tmp_name']) && is_file($_FILES['upload']['tmp_name']) ) {
		unlink ($_FILES['upload']['tmp_name']);
	}
			
} // End of the submitted conditional.
?>
	
<form enctype="multipart/form-data" action="" method="post">
	<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
	<fieldset><legend>Select a GIF, JPEG/JPG or PNG image of 512KB or smaller to be uploaded:</legend>
		<p class="file-upload-container">
			<label for="f">File:</label>
			<input id="f" type="file" name="upload" />
			<input type="submit" name="submit" value="Upload" />
		</p>
	</fieldset>
</form>