Check an uploaded file is a PDF?

Hi,

I have the following upload code:



if (is_uploaded_file ($_FILES['file']['tmp_name'])) {

		if (move_uploaded_file($_FILES['file']['tmp_name'], "../safe-files/{$_FILES['file']['name']}")) { // Moves the files over, for security.
		
		echo '<div class="success">File uploaded successfully. <a href="files.php">View uploaded files here</a>.<br /></div>';
		
		exit ();
		
	} else { // If the file couldn't be moved over.

		echo '';
		$i = FALSE;

	}

	$i = $_FILES['file']['name'];

} else {

	$i = FALSE;

}

}

However, I would like to verify that the uploaded file is a PDF.

How do I do this?

Many thanks.

If your host has php 5.3.0 or up, you have access to the FileInfo php extension.
This allows you to test the content of a file.

Before then, I don’t know what the requirements where, but probably you would have needed to install an PECL module.
http://www.php.net/manual/en/book.fileinfo.php
And more specifically: http://www.php.net/manual/en/function.finfo-file.php

Why not look at file extension? Whouldn’t pdf file end with .pdf?

There is also a pear class Mime_Type, you can look here http://pear.php.net/package/MIME_Type

You can also look at $_FILES[‘file’][‘type’] which is the mime type of uploaded file as reported by the browser.

So would it be:


if (is_uploaded_file ($_FILES['file']['tmp_name'])) && ($_FILES['file']['type'] == 'application/pdf) {

?

It’s just I heard a crazy rumour you can dupe the server into believing it’s a pdf/txt when actually it’s an exe/dll :frowning:

Sure, you can also modify the first couple of bytes in file and fool the fileinfo extension. That extension uses magic bytes in file to guess its mime type.
exe or dll file is not a problem if you take some precautions and mount the temp dir on partition with noexec option. Then it does not matter if its an exe - its still not going to be able to get executed.

exe or dll file is not a problem if you take some precautions and mount the temp dir on partition with noexec option.

OK, so what you’re saying is the code is good, but I need to CHMOD my ‘temp’ folder with the right write permissions?

No, not chmod.
The temporary directory - the dir where the php writes uploaded files (usually can be set in php.ini) should reside on a partition that is mounted with noexec

First, I assure you are using Linux.
You can create a separate partition just for temporary files. For example 500MB is more than enough. Then mount that partition with noexec option
That partition will then be secure from any time of executable injections because no script will be able to run on such partition.