Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel check if image path string is image

Tags:

php

laravel

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?

like image 937
dansan Avatar asked Dec 02 '22 16:12

dansan


1 Answers

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');
}
like image 57
craig_h Avatar answered Dec 06 '22 11:12

craig_h