Page 1 of 1

Validating a filetype during file upload

Posted: Mon Mar 15, 2004 5:08 am
by gbow
Hi

I have setup file upload systems on many of our sites. I am having problems validating the file type that has been uploaded. Obviously I would like to prevent .php and .exe files being uploaded. How can i prevent this successfully? i have tried to use the $_FILES['userfile']['type'] variable but when a php file is uploaded it displays in this variable as "text/html" which is the same as for a html document which i dont want to deny users the ability to upload. i also thought of taking the filename and taking the ending of it eg xxxx.php - if last 4 letters = .php then error or if last 4 letters = .exe then error. but this cant be the best way.

any ideas would be greatly appreciated.

cheers

Posted: Mon Mar 15, 2004 5:20 am
by twigletmac
If you want to prevent .php files from being uploaded then using the extension will be the way to go as the file's mime type is not likely to be useful. You can exclude .exe's using mime type though so the best method will probably be a mixture of the two.

First check the mime type and ensure that the file passes validation that way, then check the file extension, the [php_man]pathinfo[/php_man]() is useful to retrieve the extension.

Mac

Posted: Mon Mar 15, 2004 5:47 am
by gbow
ok thanks

i have used the mime type to block exe files but using pathinfo as you suggested does not help me to block php files as it returns the extension as html. do you have any further suggestions for blocking php files?

thanks for your help

i have used the following code now and it seems to work. ill stick with it unless you have any better suggestions?

----

$ext = substr($_FILES['userfile']['name'], -4);

if($ext == ".php" OR $ext == ".cgi") {
// DENY UPLOAD
}

----

Posted: Mon Mar 15, 2004 6:00 am
by twigletmac
Well then you're going to have to check the content of the file to look for PHP tags. Is your server set up to recognise .html files as PHP? If it's not you may not have a problem.

Mac

Posted: Mon Mar 15, 2004 6:08 am
by gbow
i dont think it is no
we just use .php files mostly anyway

is my code ^up a bit^ not suitable for blocking php files?

Posted: Mon Mar 15, 2004 6:32 am
by twigletmac
Oops sorry missed the code - working on a laptop which is making my eyes go funny.

Your code should work fine - I've never seen pathinfo() return the wrong extension before, strange.

Mac

Posted: Mon Mar 15, 2004 7:13 am
by gbow
ive never used pathinfo before but it did give html as the extension.
nevermind
ill stick with my code.
thanks for your assistance :D