In PHP, you can do this in 2 ways (if you know more than that, please let me know :))
In this example, the html form input field for the file is named “uploadedfile”.
<input type="file" name="uploadedfile" id="uploadedfile" />
In the PHP file to process the uploaded file, you can:
First method: Using $_FILES[‘fileinputname’][‘type’]
if (($_FILES["file"]["type"] == "image/gif") || ($_FILES["uploadedfile"]["type"] == "image/jpeg") || ($_FILES["uploadedfile"]["type"] == "image/pjpeg") || ($_FILES["uploadedfile"]["type"] == "image/jpg") || ($_FILES["uploadedfile"]["type"] == "image/png"))
* For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg
second method: Custom attack
$allowext = array(".gif", ".png", "jpeg", ".jpg"); $file_ext = substr(basename($_FILES['uploadedfile']['name']), -4, 4); if (in_array(strtolower($file_ext), $allowext)) { /* do your thing here */ }
I prefer using the second method as I can specify what file type extensions I can allow other people to upload. To allow other file types, all you need to do is add the extension into the $allowext array. You can do the same thing with the first method by building a array containing member types for $_FILES[“uploadedfile”][“type”], but you might need to know the MIME type for the file type that you are allowing to upload. Do you know what is the MIME type for pdf? I’m not sure. But I do know the extension for it is always “.pdf”. And for that simple reason, I stick with method 2.
Have fun 🙂
matt moeller says
happen to know what the type is for png? image/x-png and image/png don’t work properly. Atleast on a win2k3 server with php5. thanks
David says
Hi Matt,
I’m not sure about that. I *thought* image/x-png and image/png always get png covered?
If all fails, try the second method. I tend to use that since I would not need to remember the MIME types, and you can target speciafically the file type extensions.
Nick says
// Build the tmp path
$pathInfo = $pathinfo(basename($_FILES[‘uploadedvideo’][‘name’]));
$fileExt = $pathInfo[‘extension’];