Personally,I prefer to use preg_match() function:
if(preg_match("/\.(gif|png|jpg)$/", $filename))
or in_array()
$exts = array('gif', 'png', 'jpg');
if(in_array(end(explode('.', $filename)), $exts)
With in_array()
can be useful if you have a lot of extensions to validate and perfomance question.
Another way to validade file images: you can use @imagecreatefrom*()
, if the function fails, this mean the image is not valid.
For example:
function testimage($path)
{
if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
$ret = null;
switch($ext)
{
case 'png': $ret = @imagecreatefrompng($path); break;
case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
// ...
default: $ret = 0;
}
return $ret;
}
then:
$valid = testimage('foo.png');
Assuming that foo.png
is a PHP-script file with .png
extension, the above function fails. It can avoid attacks like shell update and LFI.