Request Quote

Validate post image size exceeding ‘post_max_size’ in PrestaShop

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.

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 reload the page to 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);
            location.reload();
        }
    }
});

Now, each time you try to upload an image having a size greater than PS_ATTACHMENT_MAXIMUM_SIZE, The page will be reloaded.

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close