Validation for image size

Validation for image size

alf007alf007 Posts: 37Questions: 15Answers: 0

I found a function that gives you the size of an image. Width and Height. This function is getimagesize. I want to integrate a validation using this function

->validator( function ( $file ) {
                   $size = getimagesize($file);
                    return $size[0] <= 300 && $size[1] <=450 ?
                        "The size must be 300 width and 450 height." :
                        null;
                } )

It's this the correct way to do it?

Replies

  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin

    Assuming that validator is attached to an Upload instance, then yes, that looks valid and correct.

    Custom validation documentation for uploading files is available in the manual (you probably know that given the above code, but just linking for anyone else who reads this post!).

    Allan

  • alf007alf007 Posts: 37Questions: 15Answers: 0
    edited March 2016

    Thanks for the replay. I changed my code as follows:

    ->validator( function ( $file ) {
                       $size = getimagesize($file['name']);
                        return $size[0] <= 300 && $size[1] <=450 ?
                            "The size must be 300 width and 450 height." :
                            null;
                    } )
    

    But I got a new error:

    Warning: getimagesize(WIN_20151008_13_58_09_Pro.jpg): failed to open stream: No such file or directory

    It seems to me that the function needs the correct location. Where does the Upload function put the file before it uploads it?

    Here is what I need to make it work. The path needs to be set in the function in order to read the width and the height.

    getimagesize('path_to_image');

  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin

    Try using $file['tmp_name']. THe PHP manual has details on this property.

    Allan

  • alf007alf007 Posts: 37Questions: 15Answers: 0

    It worked!

    I will share the code.

    ->validator( function ( $file ) {
                       $size = getimagesize($file['tmp_name']);
                        return $size[0] > 300 && $size[1] > 450 ?
                            "The size must be 300 width and 450 height." :
                            null;
                    } )
    
  • dataBdataB Posts: 23Questions: 5Answers: 1

    After validating the height/width how can those values be stored in separate database columns? I've tried using db() but without success.

  • allanallan Posts: 61,920Questions: 1Answers: 10,153 Site admin
    edited August 2016

    You would indeed using the db() method with a closure function (see option 3 of option 3!). That function would return the value required.

    Allan

This discussion has been closed.