Skip Navigation

[Resolved] File Upload Validation

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.

This topic contains 4 replies, has 2 voices.

Last updated by salimA 1 month, 2 weeks ago.

Assigned support staff: Waqar.

Author
Posts
#2158119

Hi,

I am trying to validate the file upload field using the below code.
when I upload with the restricted extension, the error message shows
But, When I click the submit button again, the form is submitted and data saved. What is the issue? Why does it prevent the user at the first click and allow the submission in the second click?

<?php

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.
if (( 5245 == $form_data['id']) && (isset($_FILES['wpcf-card']['type'])) && (isset($_FILES['wpcf-card']['size']))) {

//Retrieve file type
$file_type_uploaded=$_FILES['wpcf-card']['type'];

//Retrieve file size
$file_size_uploaded=$_FILES['wpcf-card']['size'];

//Validate files uploaded, make sure its PDF file type AND not more than 5000kB
if (!( ('application/pdf' == $file_type_uploaded) && ($file_size_uploaded < 5000000) )) {

$errors['card']='Sorry the file you have uploaded is not of the correct type or exceeded 100kB limit.';

}

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

#2159351

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Hi,

Thank you for contacting us and I'd be happy to assist.

I can reproduce this behaviour on my test website, only if I set the form to submit using the AJAX.

To fix this, you can change the conditional 'if' statement line in the code from:


if (( 5245 == $form_data['id']) && (isset($_FILES['wpcf-card']['type'])) && (isset($_FILES['wpcf-card']['size']))) {

To:


if ( (5245 == $form_data['id']) && (!empty($_POST['wpcf-card'])) ) {

I hope this helps and please let me know if you need any further assistance around this.

regards,
Waqar

#2161079

Hi Waqar,

Thank you, it works, but how can limit the upload size to be 2 MB only?

#2161717

Waqar
Supporter

Languages: English (English )

Timezone: Asia/Karachi (GMT+05:00)

Thanks for the update and glad that it works.

To limit the file size to 2 MB, you can replace the value "5000000" with "2097152" in your code.
( (2 x 1024) x 1024 )

#2161803

My issue is resolved now. Thank you a lot.