Skip to content

Instantly share code, notes, and snippets.

@hyptx
Last active September 8, 2023 01:23
Show Gist options
  • Save hyptx/04d44905bbe34b9bc381 to your computer and use it in GitHub Desktop.
Save hyptx/04d44905bbe34b9bc381 to your computer and use it in GitHub Desktop.
Gravity Forms Image Validation
<?php
/* Gravity Forms Image Validation ~~~~> */
/* Add to functions.php and add a css class to the input, abp-image herein */
function ter_limit_profile_image_size($validation_result){
$form = $validation_result['form'];
foreach($form['fields'] as &$field){
if(strpos($field['cssClass'],'abp-image') === false ) continue;
$is_hidden = RGFormsModel::is_field_hidden($form, $field, array());
if($is_hidden) continue;
$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['temp_filename'];
if(!$temp_filename) continue;
if(isset($_FILES[$input_name]) && !empty($_FILES[$input_name])){
$filesize = $_FILES[$input_name]['size'];
$dims = getimagesize($_FILES[$input_name]['tmp_name']);
}
elseif(file_exists($temp_location)){
$filesize = filesize($temp_location);
$dims = getimagesize($temp_filepath);
}
else continue;
list($width,$height) = $dims;
$max_size = 300;
$min_width = 750;
$min_height = 422;
if($filesize > $max_size * 1024){
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = 'Maximum banner image file size cannot exceed ' . $max_size . ' KB.';
unset(RGFormsModel::$uploaded_files[$form['id']][$input_name], $_FILES[$input_name]);
continue;
}
elseif($width < $min_width || $height < $min_height){
$validation_result['is_valid'] = false;
$field['failed_validation'] = true;
$field['validation_message'] = 'Your profile image must be at least 750px wide, and 422px tall to diplay properly.<br>The image you uploaded is: ' . $width . 'px X ' . $height . 'px';
unset(RGFormsModel::$uploaded_files[$form['id']][$input_name], $_FILES[$input_name]);
continue;
}
}
$validation_result['form'] = $form;
return $validation_result;
}
add_filter('gform_validation_6','ter_limit_profile_image_size');
?>
@hyptx
Copy link
Author

hyptx commented May 20, 2015

Don't forget to change the form id in the filter, set to #6 here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment