April 16th, 2009, 09:15 AM
Uploade File Handling
I was wondering if any devsheder's can reccomend a library or solution for handling file uploads in php.
In my case I am receiving user uploaded files using multipart/form-data post data from flash and accessing the file via the $_FILES super global.
I want to be able to virus check and validate the file types.
April 16th, 2009, 09:47 AM
Any decent virus scanner will have already scanned the files as they were being uploaded, or at least when PHP tried to access them. Otherwise it's just a matter of using the right exec/system function to call the right command-line scanner with the right arguments.
Validate file types? Most people are content to check extension, but if you want to look inside the file then it's trivial to write one yourself. Really. It's simple.
I get those character sequences from http://filext.com.
$h = fopen($_FILES["file"]["tmp_name"], "rb");
$data = fread($h, 10);
if (strncmp($data, "\x25\x50\x44\x46\x2D\x31\x2E", 7) == 0) /* is a PDF */;
if (strncmp($data, "\xFF\xD8\xFF", 3) == 0) /* is a JPEG */;
// next line isn't supposed to wrap - blame devshed for that
if (strncmp($data, "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1\x00", 9) == 0) /* is a DOC */;
if (strncmp($data, "\x4D\x5A", 2) == 0) /* is a DLL */;
Comments on this post
Last edited by requinix; April 16th, 2009 at 09:49 AM.
April 17th, 2009, 09:40 AM
I didn't want to just check the file extension or mime type so I used your method. In my case I only want gif's,jpg's and png's so I added the extra couple of binary checks using the database you posted.
All three image types made it through the filter, next I tried putting through a text file called text.txt which I had renamed it to text.gif. It did not get through.
I would have spent a long time trying to figure this out! I owe you a favour.
P.S I like the idea of passing the buck for checking viruses to anti virus software on the server.
April 17th, 2009, 09:59 AM
April 17th, 2009, 11:03 AM
You need to check the file extension as well. There is nothing stopping me from putting a gif header at the start of a PHP file, uploading it to your server and then being able to execute arbitrary PHP code on your website. PHP won't care if there is a random gif header at the start of the file, it will still execute PHP code inside of the file if the file has a .php extension.
Comments on this post
April 17th, 2009, 09:57 PM
Originally Posted by simshaun
In my case I am using Flash to upload files and it always sends the mime type application/octet-stream no matter what type of file is being used unfortunately.