CodeIgniter - File upload required validation
I found a solution that works exactly how I want.
I changed
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'required');
To
$this->form_validation->set_rules('name', 'Name', 'trim|required');
$this->form_validation->set_rules('code', 'Code', 'trim|required');
if (empty($_FILES['userfile']['name']))
{
$this->form_validation->set_rules('userfile', 'Document', 'required');
}
File Upload Validation In Codeigniter
I wrote a complete example for your problem, I hope it will help. In the following code I am using CI's Form validation callback and Form Validation Custom Error Messages.
Controller: Front.php
class Front extends CI_Controller {
public function index() {
$this->load->view('form');
}
public function upload_image() {
$this->load->library('form_validation');
if ($this->form_validation->run('user_data') == FALSE) {
$this->load->view('form');
}
else {
echo 'You form Submitted Successfully ';
}
}
public function validate_image() {
$check = TRUE;
if ((!isset($_FILES['my_image'])) || $_FILES['my_image']['size'] == 0) {
$this->form_validation->set_message('validate_image', 'The {field} field is required');
$check = FALSE;
}
else if (isset($_FILES['my_image']) && $_FILES['my_image']['size'] != 0) {
$allowedExts = array("gif", "jpeg", "jpg", "png", "JPG", "JPEG", "GIF", "PNG");
$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF);
$extension = pathinfo($_FILES["my_image"]["name"], PATHINFO_EXTENSION);
$detectedType = exif_imagetype($_FILES['my_image']['tmp_name']);
$type = $_FILES['my_image']['type'];
if (!in_array($detectedType, $allowedTypes)) {
$this->form_validation->set_message('validate_image', 'Invalid Image Content!');
$check = FALSE;
}
if(filesize($_FILES['my_image']['tmp_name']) > 2000000) {
$this->form_validation->set_message('validate_image', 'The Image file size shoud not exceed 20MB!');
$check = FALSE;
}
if(!in_array($extension, $allowedExts)) {
$this->form_validation->set_message('validate_image', "Invalid file extension {$extension}");
$check = FALSE;
}
}
return $check;
}
}
View: form.php
<!DOCTYPE html>
<html>
<head>
<title>Image Upload</title>
</head>
<body>
<h1><a href="<?= base_url() ?>">Form</a></h1>
<?php if(!empty(validation_errors())): ?>
<p><?= validation_errors() ?></p>
<?php endif; ?>
<?= form_open('front/upload_image', ['enctype' => "multipart/form-data"]) ?>
<label>Name: </label><input type="text" name="name" value="<?= set_value('name') ?>"></label>
<label>E-mail: </label><input type="email" name="email" value="<?= set_value('email') ?>"></label>
<input type="file" name="my_image">
<button type="submit">Submit</button>
<?= form_close() ?>
</body>
</html>
form_validation.php
$config = array(
'user_data' => array(
array(
'field' => 'name',
'label' => 'Name',
'rules' => 'trim|required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'trim|required|valid_email'
),
array(
'field' => 'my_image',
'label' => 'Image',
'rules' => 'callback_validate_image'
)
)
);
In above example first I am validating the name
and email
and for the Image I am calling the validate_image
function to validate it, since form_validation library does not provide image validation but i has callbacks to do custom validations, the validate_image
will check image content type then check image file size and then check image extension if any of these requirements are not fulfilled it will set error message for each requirement using set_message()
function of form_validation
library.
Codeigniter Validation Not Working When Uploading Multiple Images Using Single Input
Create the validation function yourself using callback:
public function index()
{
$this->load->helper('file');
$this->load->library('form_validation');
if($this->input->post('submit'))
{
$this->form_validation->set_rules('file', '', 'callback_file_check');
if($this->form_validation->run() == TRUE)
{
// Upload
}
}
$this->load->view('upload');
}
public function file_check($str)
{
$allowed_mime_type_arr = array('image/gif','image/jpeg','image/png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!="")
{
if(in_array($mime, $allowed_mime_type_arr))
{
return TRUE;
}
else
{
$this->form_validation->set_message('file_check', 'Please select only gif/jpg/png file.');
return FALSE;
}
}
else
{
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return FALSE;
}
}
Codeigniter validating file upload and text input in one form
What is the name of your file input? do_upload() is expecting it by default to be 'userfile', however if you have something like <input type="file" name="image"...
you will need to call $this->upload->do_upload('image')
You also need to make sure the form is set to multipart - http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
Related Topics
Select Last 20 Order by Ascending - PHP/Mysql
Why Does PHP Not Complain When I Treat a Null Value as an Array Like This
Woocommerce Add to Cart Button Redirect to Checkout
How to Set Session Timeout in Laravel
What Is a Good Method to Sanitize the Whole $_Post Array in PHP
Write a Text File and Force to Download with PHP
PHP Pdo Insert Batch Multiple Rows with Placeholders
When and Why Should $_Request Be Used Instead of $_Get/$_Post/$_Cookie
Do PHP Pdo Prepared Statements Need to Be Escaped
Running Imagemagick on Xampp 1.8.3 with Windows 7
Fatal Error: Call to a Member Function Query() on Null
Designing a Secure Auto Login Cookie System in PHP