Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JackD's avatar

Image width and height validation

Hi, is it possible for the image file to be uploaded to have its width and height validation? Like using pixel size for the image to be checked first?

regards, ci

0 likes
9 replies
bobbybouwmann's avatar

Yeah you can, but you need to do it with javascript of course. I build a small function which adds the width and height of the image to the selected image. You can then handle the validation yourself with javascript

function readImage(file, element) {
    var reader = new FileReader();
    var image  = new Image();

    reader.readAsDataURL(file);
    reader.onload = function (_file) {
        image.src = _file.target.result;
        image.onload = function() {
            $(element).data('height', this.height);
            $(element).data('width', this.width);
            $(element).data('size', ~~((file.size / 1024) / 1024));
        }
    }
}

// #background is the <input type="file" id="background">
$('#background').change(function () {
    var files = this.files;

    if (files && files[0]) {
        readImage(files[0], '#background');
    }
});

You can use the jquery Validator for example and add a rule like so

jQuery.validator.addMethod('width', function (value, element) {
    if ($(element).data('width')) {
        return $(element).data('width') >= 800;
    }

    return true;
}, 'Image needs to be wider than 800px');

jQuery Validator: http://jqueryvalidation.org/

JackD's avatar

@bobbybouwmann if i use and place that javascript in my footer, validation will work but im scared that if users tries to edit the javascript using the browser's "inspect element" they can still upload without the validation through bypassing javascript validation code?

bobbybouwmann's avatar

The only other options is upload the image, then check with validation. If the images doesn't have the correct sizes delete the image again and give a proper message to the user.

nolros's avatar

@Ci

You could use a factory pattern that could be referenced in your controller. Alternative you could create a validation request that can have validation built, but you would most likely need to create a customer validation for width and height as that is not supported in the current validation methods. Here is the controller

// inside a controller

    /**
     * Controller store example
     * 
     * @param Request $request
     */
    public static function store(Request $request)
    {
        if ($request->hasFile('photo')) {
            
            $image = ImageFactory::make(file('photo'));

            // check for truthy or instance of
            if ($image instanceof Image) {
         
                // ... do something
            }
        }
    }

class ImageFactory {

/**
 * Return a singleton if path is valid
 *
 * @param $filePath
 * @return Image
 * @throws NoFileExistException
 * @throws NotReadableException
 * @internal param $path
 */
public static function make($filePath)
{
    $imageInfo = @getimagesize($filePath);

    if (!File::exists($filePath)) {
        throw new NoFileExistException(
            "File does not exist at the given path : " . $filePath);
    }

    if ($imageInfo === false) {
        throw new NotReadableException(
            "Unable to read image from file " . $filePath
        );
    }

    If ($imageInfo[2] !== IMAGETYPE_PNG && $imageInfo[2] !== IMAGETYPE_JPEG && $imageInfo[2] !== IMAGETYPE_GIF) {

        throw new NotReadableException(
            "Unable to read image type.My app only able to decode JPG, PNG or GIF files."
        );
    }

    // create a config file and set values or use an env
    if ($imageInfo[0] < config('mycongigfile.maxWidth') && $imageInfo[1] < config('mycongigfile.maxHeight') ) {
        throw new NotReadableException(
            "Unable to read image from file " . $filePath
        );
    }

    // return image or true or whatever 
    return new Image($filePath);
}

}

JackD's avatar

Hi guys, i placed instead a Validator inside public function boot() in my AppServiceProvider.php file and it works, i have this doubt if i placed it in the correct file? though it is working but my concern is that what if i update my laravel version. Im open to any suggestions :)

regards, ci

Please or to participate in this conversation.