Script 13.3 Determining Mime Type of uploads

Output
Select an RTF document or MSWORD DOC of 512KB or smaller to be uploaded:

Source
<?php # Script 13.3 - upload_rtf

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

	// Check for an uploaded file:
	if (isset($_FILES['upload']) && file_exists($_FILES['upload']['tmp_name'])) {
		$allowed = array('text/rtf','application/msword','application/vnd.ms-excel');
		$mime = null;
		// get the mime type	
		if(function_exists('finfo_open')){
			$fileinfo = finfo_open(FILEINFO_MIME_TYPE);
			$mime = finfo_file($fileinfo, $_FILES['upload']['tmp_name']);
			finfo_close($fileinfo);
		} elseif($mime==Null) {
		    // returns the mimetype of the given file using linux command
			$filename = escapeshellarg($_FILES['upload']['tmp_name']);
			$mime = shell_exec("file -b --mime-type $filename");
		} elseif($mime==Null && function_exists('mime_content_type')) {
			// function is deprecated!
			$mime = mime_content_type($_FILES['upload']['tmp_name']);
		} elseif($mime==Null) { //least secure method if nothing else worked
			$mime = $_FILES['upload']['type'];
		}
		// Check the file:
		if($_FILES['upload']['size']>524288) {
			//file too big
			echo '<div class="message"><p class="error">Please choose a document that is less than 512KB.</p><p>The file selected is <em>'.number_format($_FILES['upload']['size']/1024,2).'KB</em>.</p></div>';
		} elseif (in_array(trim($mime), $allowed)) {	
			// It's okay!
			echo "<div class='message'><b>Thank You!</b> The selected file is an \" <em>".$mime."</em> \" document.</div>";
			// In theory, move the file over. In reality, delete the file:
			unlink($_FILES['upload']['tmp_name']);
			
		} else { 
			// Invalid type.
			echo '<div class="message"><p class="error">Please choose a document in the specified format.</p><p>The file selected is an " <em>'.$mime.'</em> " document.</p></div>';
		}		
	} else {
		echo '<p class="error">Please select a document less than 512KB to upload.</p>';
	}			
}
?>
<form enctype="multipart/form-data" action="<?php echo htmlentities( $_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING'] ); ?>" method="post">
	<input type="hidden" name="MAX_FILE_SIZE" value="524288" />
	<fieldset>
		<legend>Select an RTF document or MSWORD DOC of 512KB or smaller to be uploaded:</legend>
		<p class="file-upload-container">
			<label for="u">File:</label>
			<input id="u" type="file" name="upload" />
			<input type="submit" name="submit" value="Submit" />
		</p>
	</fieldset>
</form>