File upload validation
Jul0
Data validation is one of the easiest things in CakePHP as long as you can use the build-in validation rules. But at the moment there is no build-in rule to validate uploaded files. Today I will show you how to implement a custom validation rule and validate uploads.
Step 1: The custom validation function
To make the validation function available to all your models, you have to put it into your AppModel.
The function is designed to accept jpg, gif and png file extensions, but you can easily add other extensions in your model. Also the user is not forced to upload a file.
Filename: app/app_model.php
<?php
class AppModel extends Model {
function validFile($check, $settings) {
$_default = array(
'allowEmpty' => true,
'extensions' => array(
0 => 'jpg',
1 => 'jpeg',
2 => 'gif',
4 => 'png'
)
);
$_settings = array_merge(
$_default,
ife(
is_array($settings),
$settings,
array()
)
);
// Remove first level of Array
$_check = array_shift($check);
if($_settings['allowEmpty'] == false && $_check['size'] == 0) {
return true;
}
// No file uploaded.
if($_settings['allowEmpty'] && $_check['size'] == 0) {
return false;
}
// Check for Basic PHP file errors.
if($_check['error'] !== 0) {
return false;
}
// Use PHPs own file validation method.
if(is_uploaded_file($_check['tmp_name']) == false) {
return false;
}
// Use CakePHPs build-in rule to validate the extension
return Validation::extension(
$_check,
$_settings['extensions']
);
}
}
?>
Step 2: Create the validation rule in your model
Now we are ready to use the rule in our model. As an example we will validate the user picture in our User model. We will only accept jpg files and force the user to upload an image.
Filename: app/models/user.php
<?php
class User extends AppModel {
var $name = 'User';
var $validate = array(
'user_picture' => array(
'rule' => array(
'validFile',
array(
'allowEmpty' => false,
'extensions' => array(
0 => 'jpg',
1 => 'jpeg'
)
)
),
'error' => 'You have to upload a jpg file.'
)
);
}
?>
Step 3:
After implementing the validation rule we are ready to build the code to move the uploaded file to the corresponding folder. But I will leave this up to you. ;-)
No Comments
No comments yet.