0

I'm looking for the most secure way to determine the extension of a file that a user has sent to my server. I know I should not trust the image files sent by forms. I would start to guess it from my tmp file before moving it to my upload dir.

thank you

rudak
  • 379
  • 3
  • 16
  • possible duplicate of [PHP check file extension](http://stackoverflow.com/questions/7563658/php-check-file-extension) – Kasyx Oct 29 '14 at 13:57
  • There is no definitive way to get the extension, but using the mime-type might be your best bet, if `SplFileInfo::getExtension` proves to be unreliable – Elias Van Ootegem Oct 29 '14 at 14:12

2 Answers2

1

You can use the pathinfo function for this like:

$file = "a.jpg";
var_dump(pathinfo($file));

There will be an extension key. But i suggest you to not just validate the extension of the file, but mime type also!

vaso123
  • 12,347
  • 4
  • 34
  • 64
  • The extension returned by pathinfo on a tmp file is 'tmp', this is not what i need... – rudak Oct 29 '14 at 14:06
  • 1
    @rudak You use the function on the file name, not the temporary file name. – Alternatex Oct 29 '14 at 14:07
  • the name can be false , i think this is not very secure – rudak Oct 29 '14 at 14:09
  • @rudak Like lolka_bolka said. You can use `$_FILES['thefile']['type']` to check its mime type. – Alternatex Oct 29 '14 at 14:12
  • @rudak: please read my note below the code: " to not just validate the extension of the file, **but mime type also**" – vaso123 Oct 29 '14 at 14:13
  • 1
    yes, see here http://php.net/manual/en/function.finfo-file.php and here http://php.net/manual/en/function.image-type-to-mime-type.php and this http://stackoverflow.com/questions/2486329/how-can-i-only-allow-certain-filetypes-on-upload-in-php – vaso123 Oct 29 '14 at 15:39
0

I found this method :

public static function is_image($image_path)
{
    if (!$f = fopen($image_path, 'rb')) {
        return false;
    }

    $data = fread($f, 8);
    fclose($f);

    $unpacked = unpack("H12", $data);
    if (array_pop($unpacked) == '474946383961' || array_pop($unpacked) == '474946383761')
        return "gif";
    $unpacked = unpack("H4", $data);
    if (array_pop($unpacked) == 'ffd8')
        return "jpg";
    $unpacked = unpack("H16", $data);
    if (array_pop($unpacked) == '89504e470d0a1a0a')
        return "png";

    return false;
}

What do you think about it ? thx

rudak
  • 379
  • 3
  • 16