Skip Navigation

[Resolved] Having Problem with Restricting File Types on File Upload CRED Field

This thread is resolved. Here is a description of the problem and solution.

Problem: I would like to enforce file type restrictions on a file upload field in a Form, but the cred_form_validate hook does not provide any information about the file uploads.

Solution: Use the cred_file_upload_disable_progress_bar hook to inspect AJAX file uploads. Inspect the $_FILES superglobal to retrieve file metadata.

//*Validate for PDF on File Upload
add_filter('cred_form_ajax_upload_validate','cred_filetype_validation',10,2);
function cred_filetype_validation($error_fields, $form_data)
{
    $file_types = array('application/pdf','image/jpeg','image/png','image/tiff','image/gif');
     
     
    // Field data are field values and errors 
    list($fields,$errors)=$error_fields;
   
    //Run the rest of code for this CRED ONLY and IF the file is upload type and size are set.
     
        if (in_array($form_data['id'], [654,836,848]) && (isset($_FILES['wpcf-pedigree']['type']))) {
       
            //Retrieve file type
            $file_type_uploaded=$_FILES['wpcf-pedigree']['type'];
              
            //Validate files uploaded, make sure its PDF file type
            if (!in_array($file_type_uploaded, $file_types) ) {
                  
                //Validation failed,
                // set error message per field
                //Remove wpcf - prefix here!
                $errors['pedigree']='Sorry the file you have uploaded is not of the correct type. Accepted file types: pdf, jpg, gif, png, tiff';   
                      
            } 
       
        }
    //return result
    return array($fields,$errors);
}

Relevant Documentation:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_ajax_upload_validate

This support ticket is created 6 years, 5 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.

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 5 replies, has 2 voices.

Last updated by zacharyL 6 years, 5 months ago.

Assisted by: Christian Cox.

Author
Posts
#916310

I am trying to: Restrict file uploads to PDFs only

Link to a page where the issue can be seen: hidden link (requires login)

I expected to see: My file upload that wasn't a PDF file to be rejected

Instead, I got: No error message.

I am attempting to apply a php snippet to my functions.php based off of a response provided by Toolset support in this post:
https://toolset.com/forums/topic/types-file-custom-field-and-cred/

I needed to apply multiple CRED form IDs to the snippet, so we've modified it in such a way to allow for either of my three forms to be applied to the argument, so our function looks like this:

//*Validate for PDF on File Upload
add_filter('cred_form_validate','cred_filetype_size_validation',10,2);
function cred_filetype_size_validation($field_data, $form_data)
{
    // Field data are field values and errors 
    list($fields,$errors)=$field_data;
  
    //Run the rest of code for this CRED ONLY and IF the file is upload type and size are set.
	//var_dump($form_data['id']);
	//echo '<pre>';var_dump($_FILES);echo '</pre>';
	//exit;
    if (in_array($form_data['id'], [654,836,848]) && (isset($_FILES['wpcf-pedigree']['type']))) {
  
        //Retrieve file type
        $file_type_uploaded=$_FILES['wpcf-pedigree']['type'];
         
        //Validate files uploaded, make sure its PDF file type AND not more than 100kB
        if (!(  ('application/pdf' == $file_type_uploaded) )) {
             
            //Validation failed,
            // set error message per field
            //Remove wpcf - prefix here!
            $errors['pedigree']='Sorry the file you have uploaded is not of the correct type.';   
                 
        } 
  
    }
    //return result
    return array($fields,$errors);
}

However when applied to the context on the site, it doesn't seem to want to work, or recognize the wpcf-pedigree field at all.

This is the contents of the $_FILES array:

int(654)

array(2) {
  ["_featured_image"]=>
  array(5) {
    ["name"]=>
    string(0) ""
    ["type"]=>
    string(0) ""
    ["tmp_name"]=>
    string(0) ""
    ["error"]=>
    int(4)
    ["size"]=>
    int(0)
  }
  
["wpcf-premium-image-gallery"]=>
  array(5) {
    ["name"]=>
    array(1) {
      [0]=>
      string(0) ""
    }
    ["type"]=>
    array(1) {
      [0]=>
      string(0) ""
    }
    ["tmp_name"]=>
    array(1) {
      [0]=>
      string(0) ""
    }
    ["error"]=>
    array(1) {
      [0]=>
      int(4)
    }
    ["size"]=>
    array(1) {
      [0]=>
      int(0)
    }
  }
}

Notice there is nothing in here about the wpcf-pedigree field. And this is our problem. Just wondering if you had some insight on this.

Just a heads up, this is a live production site, though we did just launch it, so even though the field doesn't currently restrict to PDF, it does allow the user to upload a file, so an extended interruption of service would not be good for this upstart.

#916350

Hi, cred_form_validate will only be used to validate file uploads if you disable AJAX uploads using the cred_file_upload_disable_progress_bar hook. There is a different API hook you should use to validate AJAX file uploads called cred_form_ajax_upload_validate:
https://toolset.com/documentation/programmer-reference/cred-api/#cred_form_ajax_upload_validate

This should give you access to the image upload type. Click the orange + More button to see an example.

#916739

I think I edited my snippet to what the AJAX upload API call is looking for. I also tried adding additional filetypes, because the client requested additional filetypes. Still getting the same results. The client also noticed that, even though the field is not required, when the field was left empty that it kept her from submitting the form, and presented the error message I have in my PHP. Because of that, I put in an if (!empty) argument. Please let me know where I'm going wrong here.

//*Validate for PDF on File Upload
add_filter('cred_form_ajax_upload_validate','cred_filetype_validation',10,2);
function cred_filetype_validation($error_fields, $form_data)
{
	$file_types = array('application/pdf','image/jpeg','image/png','image/tiff','image/gif');
	
	
    // Field data are field values and errors 
    list($fields,$errors)=$error_fields;
  
    //Run the rest of code for this CRED ONLY and IF the file is upload type and size are set.
	//var_dump($form_data['id']);
	//echo '<pre>';var_dump($_FILES);echo '</pre>';
	//exit;
	if (!empty($_POST['wpcf-pedigree'])) {
	
		if (in_array($form_data['id'], [654,836,848]) && (isset($_FILES['wpcf-pedigree']['type']))) {
	  
			//Retrieve file type
			$file_type_uploaded=$_FILES['wpcf-pedigree']['type'];
			 
			//Validate files uploaded, make sure its PDF file type
			if (!in_array($file_type_uploaded, $file_types) ) {
				 
				//Validation failed,
				// set error message per field
				//Remove wpcf - prefix here!
				$errors['pedigree']='Sorry the file you have uploaded is not of the correct type. Accepted file types: pdf, jpg, gif, png, tiff';   
					 
			} 
	  
		}
	}
    //return result
    return array($fields,$errors);
}
#917114

The $_POST superglobal will not contain any useful information during this callback, so you should not use it in a conditional. Check the $_FILES superglobal instead:

if (!empty($_FILES['wpcf-pedigree'])) {

If you have any cred_save_data hooks in your code, be sure to remove any conditionals that validate the file field. Other than that it looks good to me.

#917116

Correction - you can safely remove that conditional completely. The isset condition in the next line will catch the case where the field and/or type are undefined.

#917535

It seems to be working now. The error message prints when an attempt to pass a file that isn't in the array is made. This makes me happy. Thank you.