3
votes

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

2
You can check ->getClientOriginalExtension() for original extenstionbipin patel
@bipinpatel, But this method only returns the extension of the file that has been uploadedShan
@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

2 Answers

0
votes

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

0
votes

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;
}