Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5557

Form validation when uploaded image size is greater than “post_max_size”

$
0
0

On the server, a setting “post_max_size” defines the length/size of the data that can be posted to the server in a single request. Whenever the form data size is greater than this value, the server discards the whole form data and no data is retrieved at the server end.

For example, If “post_max_size” is defined as “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, this limit is set in Administation->Maximum size for attached files and is stored in ‘PS_ATTACHMENT_MAXIMUM_SIZE’ configuration.

We can check the size of the image as soon as it is uploaded. 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'),
    )
);

 Now in your .js 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 image having size greater than PS_ATTACHMENT_MAXIMUM_SIZE, The page will be reloaded.


Viewing all articles
Browse latest Browse all 5557

Latest Images

Trending Articles



Latest Images