Skip to content

Instantly share code, notes, and snippets.

@nixonmedia
Created May 25, 2018 17:49
Show Gist options
  • Save nixonmedia/6f1281f67bab4fbd0c43fb0b49130edd to your computer and use it in GitHub Desktop.
Save nixonmedia/6f1281f67bab4fbd0c43fb0b49130edd to your computer and use it in GitHub Desktop.
Check the upload size of a gravity forms multi-upload
<?php
add_filter('gform_validation', 'limit_file_upload_size');
function limit_file_upload_size( $validation_result ) {
$form = $validation_result['form'];
$total_file_size = 0;
$num_files = 0;
$max_file_size = 41943040; //40MB - https://convertlive.com/u/convert/megabytes/to/bytes
foreach( $form['fields'] as &$field ){
// Add a custom CSS class to your upload field and grab onto it here...
if( strpos( $field['cssClass'], 'OAG-upload' ) === false )
continue;
//find the temporary location of the uploaded file
$input_name = 'input_' . $field['id'];
$temp_filename = RGFormsModel::get_temp_filename($form['id'], $input_name);
$temp_location = RGFormsModel::get_upload_path($form['id']) . '/tmp/' . $temp_filename['uploaded_filename'][0]['temp_filename'];
//loop through each file in a multi-file upload and add up the total file size
foreach( $temp_filename['uploaded_filename'] as $f){
$filesize = filesize( $temp_location );
$total_file_size += $filesize;
$num_files ++;
}
// return the GF error if the total size is greater than the max size
if ( $total_file_size > $max_file_size ) {
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = 'You attempted to upload a total of '. human_filesize($total_file_size, 0).'. The total size of all uploads cannot exceed 40 MB. Try compressing your files <a target="_blank" href="https://www.wikihow.com/Make-a-Zip-File">by zipping them </a> and attempt to re-upload.';
unset( RGFormsModel::$uploaded_files[$form['id']][$input_name], $_FILES[$input_name] );
continue;
}
}
GFCommon::log_debug( __METHOD__ . "(): Total Upload Size was ".$total_file_size);
$validation_result['form'] = $form;
return $validation_result;
}
function human_filesize($bytes, $decimals = 2) {
$factor = floor((strlen($bytes) - 1) / 3);
if ($factor > 0) $sz = 'KMGT';
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor - 1] . 'B';
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment