21

I have installed intervention in Laravel 5.1 and I am using the image upload and resize something like this:

Route::post('/upload', function()
{
Image::make(Input::file('photo'))->resize(300, 200)->save('foo.jpg');
});

What I dont understand is, how does intervention process the validation for the uploaded image? I mean, does intervention already has the inbuild image validation check in it or is that something I need to manually add using Laravel Validation to check for the file formats, file sizes, etc..? I have read through the intervention docs and I couldnt find info on how image validation works when using intervention with laravel.

Can someone point me in the right direction please..

Neel
  • 9,352
  • 23
  • 87
  • 128
  • 1
    You might take look at this https://laracasts.com/discuss/channels/general-discussion/validating-an-image-laravel-5 and this http://tutsnare.com/upload-files-in-laravel/ as far as I know there is no content validation in intervention. – Maytham Fahmi Aug 08 '15 at 13:14
  • Thank you @maytham Your comment certainly helped me a lot in pointing in the right direction. I have posted my solution I am using now. :) – Neel Aug 09 '15 at 13:32
  • You are welcome, here is my vote also. – Maytham Fahmi Aug 09 '15 at 14:03
  • You are very kind :) – Neel Aug 09 '15 at 17:18
  • 1
    btw I have to post that might be interesting for you as Laravel developer, protecting images and adding helpers automatically. http://stackoverflow.com/questions/31665553/how-to-automatically-register-helpers-class-in-serviceprovider/31665919#31665919 and http://stackoverflow.com/questions/30682421/how-to-protect-image-from-public-view-in-laravel-5/30682456#30682456 – Maytham Fahmi Aug 09 '15 at 18:42
  • That certainly does help. Thank you for sharing. – Neel Aug 09 '15 at 19:26
  • @maytham-ɯɐɥıλɐɯ: can you help me? – sammy Nov 15 '15 at 11:46
  • 1
    @sajad where are stuck – Maytham Fahmi Nov 15 '15 at 12:05
  • @maytham-ɯɐɥıλɐɯ: here http://stackoverflow.com/questions/33719559/send-id-user-of-choosed-user-to-database. this is my last question and will not annoy you more ... – sammy Nov 15 '15 at 12:17

5 Answers5

43

Thanks to @maytham for his comments which pointed me in the right direction.

What I found out is that the Image Intervention does not do any Validation by itself. All Image Validation has to be done before before its passed over to Image intervention for uploading. Thanks to Laravel's inbuilt Validators like image and mime types which makes the image validation really easy. This is what I have now where I am validating the file input first before passing it over to Image Intervention.

Validator Check Before Processing Intervention Image Class:

 Route::post('/upload', function()
 {
    $postData = $request->only('file');
    $file = $postData['file'];

    // Build the input for validation
    $fileArray = array('image' => $file);

    // Tell the validator that this file should be an image
    $rules = array(
      'image' => 'mimes:jpeg,jpg,png,gif|required|max:10000' // max 10000kb
    );

    // Now pass the input and rules into the validator
    $validator = Validator::make($fileArray, $rules);

    // Check to see if validation fails or passes
    if ($validator->fails())
    {
          // Redirect or return json to frontend with a helpful message to inform the user 
          // that the provided file was not an adequate type
          return response()->json(['error' => $validator->errors()->getMessages()], 400);
    } else
    {
        // Store the File Now
        // read image from temporary file
        Image::make($file)->resize(300, 200)->save('foo.jpg');
    };
 });

Hope this helps.

Neel
  • 9,352
  • 23
  • 87
  • 128
17

Simply, Integrate this to to get validation

$this->validate($request, [
    'file' => ['image', 'mimes:jpeg,png,jpg,gif,svg', 'max:2048'],
]);
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
Rahul Hirve
  • 1,109
  • 13
  • 20
4

Image Supported Formats http://image.intervention.io/getting_started/formats

The readable image formats depend on the chosen driver (GD or Imagick) and your local configuration. By default Intervention Image currently supports the following major formats.

    JPEG PNG GIF TIF BMP ICO PSD WebP

GD ✔️ ✔️ ✔️ - - - - ✔️ *

Imagick ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ ✔️ *

  • For WebP support GD driver must be used with PHP 5 >= 5.5.0 or PHP 7 in order to use imagewebp(). If Imagick is used, it must be compiled with libwebp for WebP support.

See documentation of make method to see how to read image formats from different sources, respectively encode and save to learn how to output images.

NOTE: (Intervention Image is an open source PHP image handling and manipulation library http://image.intervention.io/). This library does not validate any validation Rules, It was done by Larval Validator class

Laravel Doc https://laravel.com/docs/5.7/validation

Tips 1: (Request validation)

$request->validate([
   'title' => 'required|unique:posts|max:255',
   'body' => 'required',
   'publish_at' => 'nullable|date',
]); 

// Retrieve the validated input data...
$validated = $request->validated(); //laravel 5.7

Tips 2: (controller validation)

$validator = Validator::make($request->all(), [
    'title' => 'required|unique:posts|max:255',
    'body' => 'required',
]);

if ($validator->fails()) {
    return redirect('post/create')
        ->withErrors($validator)
        ->withInput();
}
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46
venkatskpi
  • 800
  • 6
  • 8
2

i have custum form, and this variant does not work. So i used regexp validation

like this:

  client_photo' => 'required|regex:/^data:image/'

may be it will be helpful for someone

Alex Semenov
  • 142
  • 1
  • 8
0
public function store(Request $request)
{
    $room = 1;

    if ($room == 1) {
        //image upload start
        if ($request->hasfile('photos')) {
            foreach ($request->file('photos') as $image) {
                // dd($request->file('photos'));
                $rand = mt_rand(100000, 999999);
                $name = time() . "_"  . $rand . "." . $image->getClientOriginalExtension();
                $name_thumb = time() . "_"  . $rand . "_thumb." . $image->getClientOriginalExtension();
                //return response()->json(['a'=>storage_path() . '/app/public/postimages/'. $name]);
                //move image to postimages folder
                //dd('ok');
                //  public_path().'/images/
                $image->move(public_path() . '/postimages/', $name);
                // 1280
                $resizedImage = Image::make(public_path() . '/postimages/' . $name)->resize(300, null, function ($constraint) {
                    $constraint->aspectRatio();
                });

                // save file as jpg with medium quality
                $resizedImage->save(public_path() . '/postimages/' . $name, 60);
                // $resizedImage_thumb->save(public_path() . '/postimages/' . $name_thumb, 60);
                $data[] = $name;
                       
                //insert into picture table
                $pic = new Photo();
                $pic->name = $name;
                $room->photos()->save($pic);
            }
        }

        return response()->json([
            'success' => true, 
            'message' => 'Room Created!!'
        ], 200);
    } else {
        return response()->json([
            'success' => false, 
            'message' => 'Error!!'
        ]);
    }
}
Mr.Singh
  • 1,421
  • 6
  • 21
  • 46