-1

I use file extension for validate uploading file like word excel pdf etc.?

But if user change their file extension then they can upload any file they want.

I want to function that check type of file if user change their file extension after that they should not be able to upload file.

Can any one help

Zia
  • 191
  • 12
  • 1
    What you should know about file upload security: [read this (PDF)](http://www.net-security.org/dl/articles/php-file-upload.pdf) – Fabian Schmengler Feb 15 '13 at 11:47
  • What kind of uploads are you expecting? Images or anything? – Ja͢ck Feb 15 '13 at 11:54
  • possible duplicate of [Security threats with uploads](http://stackoverflow.com/questions/11061355/security-threats-with-uploads) and [How to get the content-type of a file in PHP?](http://stackoverflow.com/questions/1232769/how-to-get-the-content-type-of-a-file-in-php) – deceze Feb 15 '13 at 12:02

3 Answers3

1

You should also check the mimetypes, for example:

$allowedMimes = array('image/gif', 'image/jpeg', 'image/jpg', 'image/png', 'image/bmp', 'image/wbmp');

//getting the mime type (it can be different from the extension) Be careful!
$imgInfo = getimagesize(imagePath);
$type = strtolower($imgInfo['mime']);

//hey dude!! This is a fake image!!
if(!in_array($type, $allowedMimes)){
    //We delete it!!
    unlink(imagePath);
}else{
    //do whatever with the image...
}

You can find more info about mime types here.

Alvaro
  • 40,778
  • 30
  • 164
  • 336
1

To be safe

Move all the files regardless of type out of the webroot.

  • Dont allow direct access to the file, use a loader to send the file to the user if you have a download feature.
  • Force the download

Have a script, download.php or whatever, get the file's ID, verify who is logged in, and if everything checks out, fetch the file, read it out to the browser, and send the appropriate download headers.

header('Content-type: application/octet-stream');
header('Content-disposition: attachment; filename=file.ext');
header("Content-Length: " . filesize('../not_in_web_root/file.ext'));
header("Content-Transfer-Encoding:  binary");
readfile('../not_in_web_root/file.ext');
exit;
  • Only accept files you want to accept by checking the extension and mimetype where possible. Its even ok to even accept php as long as you dont allow it to execute or give user direct access to it.

If your only allowing images then use a function like getimagesize(), if it has a size its an image, but still dont allow direct access to it as PHP maybe embedded into it.

If you offer a filesystem feature to your users, make it a virtual one, based on values within a database not access to the real files.

Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
0

You could possibly look at the mime type of the file? http://us2.php.net/manual/en/fileinfo.constants.php

user2075215
  • 379
  • 5
  • 21