Reading list Switch to dark mode

    Validate post image size exceeding ‘post_max_size’ in PrestaShop

    Updated 4 April 2022

    On the server, a setting “post_max_size” defines the length/size of the data in a single request to the server. When the form data is greater than this value, the server discards whole data and you cannot apply proper validation.

    For example, If the value of “post_max_size” is “8M” in php.ini, and you try to upload an image of size 9 MB, then this issue will occur and you will not get any data in $_POST or $_FILES.

    In this case, you cannot validate any of the data at the server end as the server discards whole form data.

    To avoid this issue, you have to consider a data size limit by which you will validate the data in javascript before form submission. This limit should be equivalent to “post_max_size”.

    In PrestaShop, you can find the setting for this limit. Go to Administration-Maximum size for attached files. PrestaShop saves this limit value in ‘PS_ATTACHMENT_MAXIMUM_SIZE’ configuration.

    Searching for an experienced
    Prestashop Company ?
    Find out More

    You can check the size of the image as soon as you select the image to upload. If this size exceeds the limit, we can show alert and reset the file input.

    First, assign two variables for javascript in your controller:

    Media::addJsDef(
        array(
            'filesizeError' => $this->l('File exceeds maximum size.'),
            'maxSizeAllowed' => Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE'),
        )
    );

    Your javascript file will use these variables. It will use “maxSizeAllowed” to compare size and “filesizeError” to show error message. Now in your javascript file, write this code:

    $('input[type="file"]').on('change', function() {
        if (typeof this.files[0] != 'undefined') {
            if (this.files[0].size > maxSizeAllowed*1000000) {
                alert(filesizeError);
                this.value = "";
            }
        }
    });

    Now, each time you try to upload an image having a size greater than PS_ATTACHMENT_MAXIMUM_SIZE, the page will show an alert and file input will reset.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home