Reputation: 249
I'm passing an image path as a GET paremeter when a link is clicked, but I need to check if this is an image for security reasons.
When I try this code, where $fileName
is '15612.jpg':
$fileName = $_GET['fileName'];
$image = array('file' => File::get('unverified-images/'.$fileName));
$rules = array('file' => 'image');
$validator = Validator::make($image, $rules);
if ($validator->fails()) {
Session::flash('error', 'Not an image');
return Redirect::to('controlpanel');
}
All .jpg files I have tested give 'Not an image', but when I try with a .txt file it doesn't give an error, why is this? I'm guessing im doing something wrong, as the validator is supposed to fail when it's not an image, right?
I know the validator takes Input::file()
instead of File::get()
, but how can I use that if I'm not using a form?
Upvotes: 7
Views: 25037
Reputation: 4425
Other way to check if it is an image is getting the extension of the file like this with php explode
function:
PHP:
$imageExtensions = ['jpg', 'jpeg', 'gif', 'png', 'bmp', 'svg', 'svgz', 'cgm', 'djv', 'djvu', 'ico', 'ief','jpe', 'pbm', 'pgm', 'pnm', 'ppm', 'ras', 'rgb', 'tif', 'tiff', 'wbmp', 'xbm', 'xpm', 'xwd'];
$explodeImage = explode('.', 'path/image.jpg');
$extension = end($explodeImage);
if(in_array($extension, $imageExtensions))
{
// Is image
}else
{
// Is not image
}
This work for me, regards!
Here you can find an array of all file extensions: click here
Upvotes: 5
Reputation: 32714
This may be a case of avoiding the validator, and doing the check yourself, so you could do:
$allowedMimeTypes = ['image/jpeg','image/gif','image/png','image/bmp','image/svg+xml'];
$contentType = mime_content_type('path/to/image');
if(! in_array($contentType, $allowedMimeTypes) ){
Session::flash('error', 'Not an image');
return Redirect::to('controlpanel');
}
Upvotes: 14