Skip Navigation

[Resolved] ajax_upload_validate for repetitive images

This support ticket is created 4 years, 11 months ago. There's a good chance that you are reading advice that it now obsolete.

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.

Our next available supporter will start replying to tickets in about 2.09 hours from now. Thank you for your understanding.

Sun Mon Tue Wed Thu Fri Sat
8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 8:00 – 12:00 - -
13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 13:00 – 17:00 - -

Supporter timezone: America/New_York (GMT-04:00)

This topic contains 8 replies, has 2 voices.

Last updated by Christian Cox 4 years, 11 months ago.

Assisted by: Christian Cox.

Author
Posts
#1400685

Hi, I'm trying to setup cred_form_ajax_upload_validate for repetitive images. I used an example I found on the forum and it works fine for featured and another custom image, but not for repetitive. How should I set it up?

I also want to add image width and height limit to 1280px, how can I do it?

add_filter('cred_form_ajax_upload_validate','my_validation',10,2);
function my_validation($error_fields, $form_data)
{
    //field data are field values and errors
    list($fields,$errors)=$error_fields;
    //validate if specific form
    if ($form_data['id']==3498)
    { 
        if ($fields['_featured_image']['field_data']['size'] > 1000000)
        {
      		log_me('F Img Size: '.$fields['_featured_image']['file_data']['size']);
            //set error message for featured image
            $errors['_featured_image'] = 'Wrong size image';
        }     
        if ($fields['wpcf-logo']['field_data']['size'] > 1000000)
        {
      		log_me('logo Size: '.$fields['wpcf-logo']['file_data']['size']);
            //set error message for featured image
            $errors['logo'] = 'Wrong size image';
        }    
        if ($fields['wpcf-gallery'][0]['field_data']['size'] > 1000000)
        {
      		log_me('gallery Size: '.$fields['wpcf-gallery'][0]['file_data']['size']);
            //set error message for featured image
            $errors['gallery'][0] = 'Wrong size image';
        }
    }
    //return result
    return array($fields,$errors);
}
#1400687

I've tried to check width and height with adding also this code:

    
      
      $target_max_width = 1280;
      $target_max_height = 720;
      $check = getimagesize( $_FILES['_featured_image']['tmp_name'] );
      if ( $check !== false ) {
        // check the dimensions only, independent of the orientation.
        // if the height is greater than the width, switch the values for comparison.
        $width = ($check[0] >= $check[1]) ? $check[0] : $check[1];
        $height = ($check[1] < $check[0]) ? $check[1] : $check[0];

        if ( $width > $target_max_width || $height > $target_max_height ) {
          $errors['_featured_image'] = __("Your image exceeds the permissible dimensions. Please resize and try again.");
        }
      }    
      $target_max_width = 100;
      $target_max_height = 100;
      $check = getimagesize( $_FILES['wpcf-logo']['tmp_name'] );
      if ( $check !== false ) {
        // check the dimensions only, independent of the orientation.
        // if the height is greater than the width, switch the values for comparison.
        $width = ($check[0] >= $check[1]) ? $check[0] : $check[1];
        $height = ($check[1] < $check[0]) ? $check[1] : $check[0];

        if ( $width > $target_max_width || $height > $target_max_height ) {
          $errors['logo'] = __("Your image exceeds the permissible dimensions. Please resize and try again.");
        }
      }  

I get this on debug log:

[05-Dec-2019 12:38:21 UTC] PHP Notice: Undefined index: wpcf-logo in /home2/naturdk1/public_html/boxelderlocals/wp-content/toolset-customizations/custom-forms.php on line 114
[05-Dec-2019 12:38:21 UTC] PHP Warning: getimagesize(): Filename cannot be empty in /home2/naturdk1/public_html/boxelderlocals/wp-content/toolset-customizations/custom-forms.php on line 114

#1401011

The main issue is that repeating field keys in the $fields array are formatted to look like an array syntax. I would try something like this to validate an image size. It should work for single fields or repeating fields:

add_filter('cred_form_ajax_upload_validate', 'toolset_rept_img_size_restriction',10,2);
function toolset_rept_img_size_restriction($error_fields, $form_data) {
  $forms = array( 123, 456 ); // comma-separated list of form IDs
  $slug = 'book-rept-img-1'; // change to your field slug, no wpcf- prefix here
  $error_string = 'Sorry the file you have uploaded is not the right size';
  $unknown_error_string = 'An unknown error occurred while processing this image';
  $target_max_width = 1280;
  $target_max_height = 720;
  $tmpimg = -1;
  
  // you shouldn't need to edit anything below here

  // Field data are field values and errors
  list($fields,$errors)=$error_fields;

  if ( in_array($form_data['id'], $forms ) ) {
    $keys = array_keys( $fields );
    // determine if this is the correct field based on $slug
    // then get the temporary file name for validation process
    if( isset( $fields[ 'wpcf-' . $slug ] ) ) {
      // this is a single field, not a repeating field
      // the field slug matches
      $tmpimg = $fields[ 'wpcf-' . $slug]['field_data']['tmp_name'];
    } else {
      // this is not the single field, but could be a repeating field
      if( strpos( $keys[0], 'wpcf-' . $slug . '[' ) === 0 ) {
        // for example, repeating field wpcf-slug[0] or wpcf-slug[1]
        // now we know that the repeating field has the right slug
        $tmpimg = $fields[ $keys[0] ]['field_data']['tmp_name'];
      }
    }

    // If there's no tmpimg this isn't the right field
    // no validation needed
    if ( $tmpimg === -1 ) {
      return array($fields,$errors);
    }


    // Retrieve img size of tmpimg and validate it.
    $check = getimagesize( $tmpimg );
    if ( $check !== false ) {
      // check the dimensions only, independent of the orientation.
      // if the height is greater than the width, switch the values for comparison.
      $width = ($check[0] >= $check[1]) ? $check[0] : $check[1];
      $height = ($check[1] < $check[0]) ? $check[1] : $check[0];

      if ( $width > $target_max_width || $height > $target_max_height ) {
        $errors[ $keys[0] ] = __($error_string);
      }
    }else{
      // unable to get image size from tmp file name. not sure why.
      $errors[ $keys[0] ] = __($unknown_error_string);
    }
  }
  //return result
  return array($fields,$errors);
}
#1401035

Thanks for the code.

Does it works also with _featured_image?

How can I integrate file size check for all find of images?

#1401079

I think if you use a variable for the prefix, you could make it work with both featured images and image custom fields:

add_filter('cred_form_ajax_upload_validate', 'toolset_feat_img_size_restriction',10,2);
function toolset_feat_img_size_restriction($error_fields, $form_data) {
  $forms = array( 123, 456, 28 );
  $prefix = ''; // set to an empty string for featured image or wpcf- for a Types custom field
  $slug = '_featured_image'; // slug of field without wpcf- prefix
  $error_string = 'Sorry the file you have uploaded is not the right size';
  $unknown_error_string = 'An unknown error occurred while processing this image';
  $tmpimg = -1;
  $target_max_width = 1280;
  $target_max_height = 720;

  // Field data are field values and errors
  list($fields,$errors)=$error_fields;

  if ( in_array($form_data['id'], $forms ) ) {
    $keys = array_keys( $fields );
    // determine if this is the correct field based on $slug
    // then get the temporary file name for validation process
    if( isset( $fields[ $prefix . $slug ] ) ) {
      // this is a single field, not a repeating field
      // the field slug matches
      $tmpimg = $fields[ $prefix . $slug]['field_data']['tmp_name'];
    } else {
      // this is not the single field, but could be a repeating field
      if( strpos( $keys[0], $prefix . $slug . '[' ) === 0 ) {
        // for example, repeating field wpcf-slug[0] or wpcf-slug[1]
        // now we know that the repeating field has the right slug
        $tmpimg = $fields[ $keys[0] ]['field_data']['tmp_name'];
      }
    }

    // If there's no tmpimg this isn't the right field
    // no validation needed
    if ( $tmpimg === -1 ) {
      return array($fields,$errors);
    }


    // Retrieve img size of tmpimg and validate it.
    $check = getimagesize( $tmpimg );
    if ( $check !== false ) {
      // check the dimensions only, independent of the orientation.
      // if the height is greater than the width, switch the values for comparison.
      $width = ($check[0] >= $check[1]) ? $check[0] : $check[1];
      $height = ($check[1] < $check[0]) ? $check[1] : $check[0];

      if ( $width > $target_max_width || $height > $target_max_height ) {
        $errors[ $keys[0] ] = __($error_string);
      }
    }else{
      // unable to get image size from tmp file name. not sure why.
      $errors[ $keys[0] ] = __($unknown_error_string);
    }
  }
  //return result
  return array($fields,$errors);
}

For a Types image field, the prefix and slug would look like this:

  $prefix = 'wpcf-'; // set to an empty string for featured image or wpcf- for a Types custom field
  $slug = 'some-field-slug'; // slug of field without wpcf- prefix
#1401183

Ok , so I've to create 2 different functions for featured image and custom images, correct?

I also want to limit the upload weight of images to not more then 500Kb. How can I initegrate it in the function?

cheers

#1402157

Ok , so I've to create 2 different functions for featured image and custom images, correct?
As it is written here, yes. You can use the code example here to create your own custom solution if you'd like to combine them into one function.

I also want to limit the upload weight of images to not more then 500Kb. How can I initegrate it in the function?
If you want to check the filesize of the image, you can find that information in the same array as the tmp_name key:

$tmpimg = $fields[ $prefix . $slug]['field_data']['tmp_name'];
$filesize = $fields[ $prefix . $slug]['field_data']['size'];

The code example I provided is just a general guideline for creating your own custom solution.

#1404097

Hi, I setup my code, I've added some log_me(); messages so I can see on debug it works fine. It gets all the variables correctly and the output is correct, but it is not working fine on the form. It doesn't block the upload of the image based on image or file size.

This is the code I setup


/**
 * Customise validate
*/

function img_validation($fields, $errors, $error_fields, $form_data, $prefix, $slug, $error_string, $error_string2, $unknown_error_string, $tmpimg, $target_max_width, $target_max_height) {

  $keys = array_keys( $fields );
  // determine if this is the correct field based on $slug
  // then get the temporary file name for validation process
  if( isset( $fields[ $prefix . $slug ] ) ) {
    // this is a single field, not a repeating field
    // the field slug matches
    $tmpimg = $fields[ $prefix . $slug]['field_data']['tmp_name'];
    $filesize = $fields[ $prefix . $slug]['field_data']['size'];
    
      log_me('$tmpimg: '.$tmpimg);
    
      log_me('$filesize: '.$filesize);

  } else {
    // this is not the single field, but could be a repeating field
    if( strpos( $keys[0], $prefix . $slug . '[' ) === 0 ) {
      // for example, repeating field wpcf-slug[0] or wpcf-slug[1]
      // now we know that the repeating field has the right slug
      $tmpimg = $fields[ $keys[0] ]['field_data']['tmp_name'];
      $filesize = $fields[ $keys[0] ]['field_data']['size'];
    }
  }

  // If there's no tmpimg this isn't the right field
  // no validation needed
  if ( $tmpimg === -1 ) {
    return array($fields,$errors);
  }


  // Retrieve img size of tmpimg and validate it.
  $check = getimagesize( $tmpimg );
  if ( $check !== false ) {
    // check the dimensions only, independent of the orientation.
    // if the height is greater than the width, switch the values for comparison.
    $width = ($check[0] >= $check[1]) ? $check[0] : $check[1];
    $height = ($check[1] < $check[0]) ? $check[1] : $check[0];
      log_me('$width: '.$width);
    
      log_me('$height: '.$height);

    if ( $width > $target_max_width || $height > $target_max_height ) {
      $errors[ $keys[0] ] = __($error_string);
      log_me('$width $keys[0]: '.$keys[0]);
      log_me('$width > $target_max_width');
    }
  } else {
    // unable to get image size from tmp file name. not sure why.
    $errors[ $keys[0] ] = __($unknown_error_string);
  } 


  // Retrieve file size of $filesize and validate it.
  if ($filesize >= 1000000) {
      log_me('$filesize $keys[0]: '.$keys[0]);
    log_me('$filesize >= 1000000: '.$filesize);
    $errors[ $keys[0] ] = __($error_string2);
  }    
  return array($fields,$errors);

}


add_filter('cred_form_ajax_upload_validate','my_validation',10,2);
function my_validation($error_fields, $form_data) {
  //field data are field values and errors
  list($fields,$errors)=$error_fields;
  
  $forms = array( 3498 );

  // Field data are field values and errors
  list($fields,$errors)=$error_fields;

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


    /* wpcf-logo */
    $prefix = 'wpcf-'; // set to an empty string for featured image or wpcf- for a Types custom field
    $slug = 'logo'; // slug of field without wpcf- prefix
    $error_string = 'Image max size 150x150px)';
    $error_string2 = 'File max size 1 Mbyte';
    $unknown_error_string = 'An unknown error occurred while processing this image';  
    $tmpimg = -1;
    $target_max_width = 150;
    $target_max_height = 150;    
    img_validation($fields, $errors, $error_fields, $form_data, $prefix, $slug, $error_string, $error_string2, $unknown_error_string, $tmpimg, $target_max_width, $target_max_height);


    /* _featured_image */
    $prefix = ''; // set to an empty string for featured image or wpcf- for a Types custom field
    $slug = '_featured_image'; // slug of field without wpcf- prefix
    $error_string = 'Image max size 1280x720px)';
    $error_string2 = 'File max size 1 Mbyte';
    $unknown_error_string = 'An unknown error occurred while processing this image';  
    $tmpimg = -1;
    $target_max_width = 1280;
    $target_max_height = 720;      
    img_validation($fields, $errors, $error_fields, $form_data, $prefix, $slug, $error_string, $error_string2, $unknown_error_string, $tmpimg, $target_max_width, $target_max_height);
    
    /* wpcf-gallery */
    $prefix = 'wpcf-'; // set to an empty string for featured image or wpcf- for a Types custom field
    $slug = 'gallery'; // slug of field without wpcf- prefix
    $error_string = 'Image max size 1280x720px)';
    $error_string2 = 'File max size 1 Mbyte';
    $unknown_error_string = 'An unknown error occurred while processing this image';  
    $tmpimg = -1;
    $target_max_width = 1280;
    $target_max_height = 720;      
    img_validation($fields, $errors, $error_fields, $form_data, $prefix, $slug, $error_string, $error_string2, $unknown_error_string, $tmpimg, $target_max_width, $target_max_height);
    
  }
}

This is what I'm getting on debug.log:

[10-Dec-2019 11:05:45 UTC] $tmpimg: /tmp/phphuCPyl
[10-Dec-2019 11:05:45 UTC] $filesize: 1194161
[10-Dec-2019 11:05:45 UTC] $width: 2592
[10-Dec-2019 11:05:45 UTC] $height: 1944
[10-Dec-2019 11:05:45 UTC] $width $keys[0]: _featured_image
[10-Dec-2019 11:05:45 UTC] $width > $target_max_width
[10-Dec-2019 11:05:45 UTC] $filesize $keys[0]: _featured_image
[10-Dec-2019 11:05:45 UTC] $filesize >= 1000000: 1194161
[10-Dec-2019 11:05:45 UTC] $tmpimg: /tmp/phphuCPyl
[10-Dec-2019 11:05:45 UTC] $filesize: 1194161
[10-Dec-2019 11:05:45 UTC] $width: 2592
[10-Dec-2019 11:05:45 UTC] $height: 1944
[10-Dec-2019 11:05:45 UTC] $width $keys[0]: _featured_image
[10-Dec-2019 11:05:45 UTC] $width > $target_max_width
[10-Dec-2019 11:05:45 UTC] $filesize $keys[0]: _featured_image
[10-Dec-2019 11:05:45 UTC] $filesize >= 1000000: 1194161

Where is the problem?

thanks

#1406007

The main thing I see is that my_validation never returns anything. my_validation must return an array of $fields and $errors:

return array($fields,$errors);

I can see the return statements have been moved into an external function img_validation. The PHP 'return' operator only returns one level of depth in the call stack. In other words a return inside img_validation only returns to my_validation. It does not also return more levels. To do that you could return the call to img_validation like this:

// add a return in my_validation
return img_validation($fields, $errors, $error_fields, $form_data, $prefix, $slug, $error_string, $error_string2, $unknown_error_string, $tmpimg, $target_max_width, $target_max_height);

This would force my_validation to return the value returned by img_validation...but then problem #2 happens.

The second thing I see is that there is no conditional flow for the 3 different img_validation calls for wpcf-logo, wpcf-gallery, and _featured_image. So if you return img_validation in the wpcf-logo block, the wpcf-logo validation will be applied to all types of image uploads. The wpcf-gallery and _featured_image validations will never be applied to anything, because the function has already returned.

Does this help explain the problem?