Prevent large image uploads

I want to prevent users in my blog from uploading large size images. And I mean large in px size not MB. Max Upload is set to 8MB which should be ok but I wan’t to prevent uploading for images larger than 3000x3000px.

Is there any hook I am missing that I could write a function for to tell users their image is too large?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You have a few different solutions available here:

Automatically scaling down

If you just do not want to store huge amounts of image data on your webspace, I’d recommend the Plugin Imsanity. This automatically scales down the uploaded images, even if they are too big.

Forbid large uploads

In this case the user has more work to do, as they will have to scale down the images on their own. You could filter the wp_handle_upload_prefilter:

add_filter('wp_handle_upload_prefilter', 'f711_image_size_prevent');
function f711_image_size_prevent($file) {
    $size = $file['size'];
    $size = $size / 1024; // Calculate down to KB
    $type = $file['type'];
    $is_image = strpos($type, 'image');
    $limit = 5000; // Your Filesize in KB

    if ( ( $size > $limit ) && ($is_image !== false) ) {
        $file['error'] = 'Image files must be smaller than '.$limit.'KB';
    }

    return $file;

}

Change the PHP values

This one is fairly straight forward, you just have to set max_upload_size in your .htaccess or php.ini.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x