3

How to verify that an image is really an "Image" or a PDF is really a "PDF document" during the upload?

I observed a hack attempt to upload some files with jpg extension which has a picture preview but when I tried to open this file in an editor I saw php codes!

My concern is about:

How can I verify that a file is a real file?

Im using laravel framework, I tested with image mimes validation as shown below:

$inputs = array('image'=>$request->file('file'));
$rules = array(
          'image' => 'mimes:jpeg,jpg,png,gif|required|max:10000'
        );

$validator = Validator::make($inputs, $rules);
    if ($validator->fails()){
        die('validation failed');
    }else{
        die('validation Passed');
    }

But this validation always pass if I try to upload the invalid jpeg file with some php injected codes!

Update: invalid jpeg file attached enter image description here

Martin54
  • 1,349
  • 2
  • 13
  • 34
Shan
  • 1,081
  • 1
  • 12
  • 35
  • You can check ->getClientOriginalExtension() for original extenstion – bipin patel Nov 25 '17 at 13:38
  • @bipinpatel, But this method only returns the extension of the file that has been uploaded – Shan Nov 25 '17 at 13:45
  • https://stackoverflow.com/questions/6484307/how-to-check-if-an-uploaded-file-is-an-image-without-mime-type – GoatHater Nov 25 '17 at 15:16
  • @GoatHater i checked the getImageSize() and got the resulting array as : , Array ( [0] => 317 [1] => 40 [2] => 1 [3] => width="317" height="40" [bits] => 6 [channels] => 3 [mime] => image/gif ). which seems valid for "the invalid file" – Shan Nov 26 '17 at 06:48

2 Answers2

0

If you want to verify that it is an image, add the 'image' rule to your $rules array:

$rules = array(
      'image' => 'image|mimes:jpeg,jpg,png,gif|required|max:10000'
);

https://laravel.com/docs/master/validation#rule-image

İlker Ergün
  • 68
  • 2
  • 7
0

At last, i decided to check the file manually using the method - file_get_contents(). I don't know whether this is an optimal solution. awaiting suggestions & recommendations :

public function validateFileContents($file,$needlesArray=null){
    if(empty($needlesArray)){
        $needlesArray = ['<?php','eval','base','gzuncomp'];
    }
    foreach($needlesArray as $needle){
        if( strpos(file_get_contents($file),$needle) !== false) {
            return false;
            break;
        }
    }
    return true;
}
Shan
  • 1,081
  • 1
  • 12
  • 35