Skip Navigation

[Resolved] Need help in setting limitations on images size and number of images

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

No supporters are available to work today on Toolset forum. Feel free to create tickets and we will handle it as soon as we are online. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 17 replies, has 2 voices.

Last updated by Minesh 3 months, 3 weeks ago.

Assisted by: Minesh.

Author
Posts
#2677803

Jay

Hi there,

I am trying to limit image upload size to less than 2MB and want to limit user to upload only 100 max images there, Can you please suggest me how to do that as I tried custom code but it did not work.

Appreciate your help on that

Thanks

#2677823

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Can you please tell me where exactly you want to apply those restrictions? Do you want to apply those restrictions while using Toolset post form?

Can you please share all those required details and I will be happy to guide you in the right direction.

Could you please send me debug information that will help us to investigate your issue.
=> https://toolset.com/faq/provide-debug-information-faster-support/

#2677985

Jay

Hello Minesh,

yes, I am using Toolset post form has a image field with "Allow multiple instances of this field" and I want to add validation for each image size not more then 2mb and the limit number of images to upload like 20 images.

Is there any way to do this?

Thanks.

#2677992

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

. You can add the following code to "Custom Code" section offered by Toolset:
- https://toolset.com/documentation/programmer-reference/adding-custom-code/using-toolset-to-add-custom-code/#adding-custom-php-code-using-toolset

add_filter('cred_form_validate','func_validate_image_repeating_field_size',10,2);
function func_validate_image_repeating_field_size($error_fields, $form_data) {
        
      list($fields,$errors)=$error_fields;
       // target form IDs
      $forms = array( 999999 );
        
if (in_array($form_data['id'], $forms ) ) {
      
/// target form field
$form_fields = array("wpcf-book-image");
   
/// allowed size
$number_of_mb_limit = 2;
$max_size    = $number_of_mb_limit * (1024 * 1024);

/// allowed number of images
$allowed_count = 20;

 
  foreach($form_fields as $k=>$v):
   
         $count = count($_FILES[$v]['type']);
          
        for($i=0;$i<$count;$i++) {
                      $size = $_FILES[$v]['size'][$i];
           
            if ( ( $size >= $max_size  and   $count > $allowed_count) ) {
                $errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit and upload maximum  $allowed_count files.';
                return array($fields,$errors);

            }else if($size >= $max_size){
                        $errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit.';
                       return array($fields,$errors);
            }else if($count > $allowed_count){
                               $errors[$v] = 'You are allowed to upload maximum  $allowed_count files.';
                              return array($fields,$errors);
          }

        }
   endforeach;
   
 }
return array($fields,$errors);
}

Where:
- Replace 999999 with your original form ID
- Replace wpcf-myimage with your original image field. If you have image field "book-image" then you should replace the $form_fields variable value as: $form_fields = array("wpcf-book-image");

More info:
- https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_validate

#2677993

Jay

I have created custom code as you mentioned above, and changed form id and field name. I tried to upload 5mb picture and its successfully uploaded instead of giving error. Can you please check once the code and let me know.

<?php
/**
* New custom code snippet (replace this with snippet description).
*/

toolset_snippet_security_check() or die( 'Direct access is not allowed' );

// Put the code of your snippet below this comment.

add_filter('cred_form_validate','func_validate_image_repeating_field_size',10,2);
function func_validate_image_repeating_field_size($error_fields, $form_data) {

list($fields,$errors)=$error_fields;
// target form IDs
$forms = array( 1867 );

if (in_array($form_data['id'], $forms ) ) {

/// target form field
$form_fields = array("wpcf-crew-member-images");

/// allowed size
$number_of_mb_limit = 2;
$max_size = $number_of_mb_limit * (1024 * 1024);

/// allowed number of images
$allowed_count = 2;

foreach($form_fields as $k=>$v):

$count = count($_FILES[$v]['type']);

for($i=0;$i<$count;$i++) {
$size = $_FILES[$v]['size'][$i];

if ( ( $size >= $max_size and $count > $allowed_count) ) {
$errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit and upload maximum $allowed_count files.';
return array($fields,$errors);

}else if($size >= $max_size){
$errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit.';
return array($fields,$errors);
}else if($count > $allowed_count){
$errors[$v] = 'You are allowed to upload maximum $allowed_count files.';
return array($fields,$errors);
}

}
endforeach;

}
return array($fields,$errors);
}

#2677994

Jay
toolset.PNG

this is the field screenshot.

#2677999

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Can you please share problem URL and admin access details and let me see whats going wrong with your setup.

*** Please make a FULL BACKUP of your database and website.***
I would also eventually need to request temporary access (WP-Admin and FTP) to your site. Preferably to a test site where the problem has been replicated if possible in order to be of better help and check if some configurations might need to be changed.

I have set the next reply to private which means only you and I have access to it.

#2678171

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

I found that you are using media uploader to upload the images.

Do you want to use media uploader as it will be bit complicated to manage file uploads and restrict number of files and size using that.

#2678448

Jay

okay, can you please tell me what I can use for achieve this requirements?

#2678452

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

- is it ok for you to not use Media uploader and allow the users to upload images using file upload field?

We can restrict anyway but at some point you may have to compromise with your requirement.

I've added the following code to your theme's functions.php file:

add_filter('wp_handle_upload_prefilter', 'limit_wp_handle_upload_prefilter');

function limit_wp_handle_upload_prefilter($file) {
	
			$allowed_number_of_img_uploads = 20;

	if(!is_admin()) {
			
			// restrict number of file uploads using media uploader

			if ($file['type']=='application/octet-stream' && isset($file['tmp_name'])) {

			$file_size = getimagesize($file['tmp_name']);

			if (isset($file_size['error']) && $file_size['error']!=0) {

			$file['error'] = "Unexpected Error: {$file_size['error']}";

			return $file;

			} else {

			$file['type'] = $file_size['mime'];

			}

			}

			if ($post_id = (isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : false)) {

					if (count(get_posts("post_type=attachment&post_parent={$post_id}"))> $allowed_number_of_img_uploads ) {

						$file['error'] = "Sorry, you cannot upload more than allowed number ($allowed_number_of_img_uploads) image(s).";
					}

			}
			
			
			// restrict image size using media uploader

			
			 $user = wp_get_current_user(); 
	 //Obtaining the role 
	 $roles = ( array ) $user->roles; 
	 
    // Set the desired file size limit
    $file_size_limit = 2048 ; // 2MB in KB


        $current_size = $file['size'];
        $current_size = $current_size / 1024; //get size in KB

        if ( $current_size > $file_size_limit ) {
            $file['error'] = 'ERROR: File size must be no more than 2 MB.';
        }

    }
			

return $file;

}

Where:
- You can adjust the error message as per your requirement.

Can you test and check if this is enough per your your requirement to restrict image size and number of files uploaded using media uploader.

#2678455

Jay

yes, it's okay to use file upload field. Is there anything need to change in field settings?

#2678465

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

No - the code above I shared is while you use the form setting "Use the WordPress Media Library manager for image, video, audio, or file fields".

Have you checked - does it working as expected for you when you try to upload more than 2MB image and try to upload more than 20 image files?

If you do not want to use media uploader then we need to disable the above shared code that I've added to your theme's functions.php file and then you can use the code I shared before with my previous reply:
- https://toolset.com/forums/topic/need-help-in-setting-limitations-on-images-size-and-number-of-images/#post-2677992

#2678473

Jay

Image size functionality working fine, but still I can upload more then 20 images, also there is add new option as well. Need to hide that add new as well.

#2678475

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Are you talking about media uploader? If yes - then as I shared you will have to compromise with media uploader and uncheck the setting with your form "Use the WordPress Media Library manager for image, video, audio, or file fields" and save your form.

Then disable the filter code I shared for "wp_handle_upload_prefilter" and enable the filter hook "cred_form_validate" to validate the number of files/image uploaded and file size:
- https://toolset.com/forums/topic/need-help-in-setting-limitations-on-images-size-and-number-of-images/#post-2677992

#2678610

Jay

Hello Minesh

I have unchecked the media uploader field and add this code into function.php file, I have set the limit of images : 2 and size is 2mb, but It's not working as I can upload 3 images and each image size is 6mb. Can you please check the code below.

add_filter('cred_form_validate','func_validate_image_repeating_field_size',10,2);
function func_validate_image_repeating_field_size($error_fields, $form_data) {

list($fields,$errors)=$error_fields;
// target form IDs
$forms = array( 1857 );

if (in_array($form_data['id'], $forms ) ) {

/// target form field
$form_fields = array("wpcf-crew-member-images");

/// allowed size
$number_of_mb_limit = 2;
$max_size = $number_of_mb_limit * (1024 * 1024);

/// allowed number of images
$allowed_count = 2;

foreach($form_fields as $k=>$v):

$count = count($_FILES[$v]['type']);

for($i=0;$i<$count;$i++) {
$size = $_FILES[$v]['size'][$i];

if ( ( $size >= $max_size and $count > $allowed_count) ) {
$errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit and upload maximum $allowed_count files.';
return array($fields,$errors);

}else if($size >= $max_size){
$errors[$v] = 'Sorry the file you have uploaded exceeded 2MB limit.';
return array($fields,$errors);
}else if($count > $allowed_count){
$errors[$v] = 'You are allowed to upload maximum $allowed_count files.';
return array($fields,$errors);
}

}
endforeach;

}
return array($fields,$errors);
}

This ticket is now closed. If you're a WPML client and need related help, please open a new support ticket.