how to upload multiple image with different input file in codeigniter - php

I want to upload multiple image with different input file with array name.
view :
<form action="" enctype="multipart/form-data" method="post">
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input name="picture[]" class="form-control" style="padding-top: 0;" type="file"/>
<input type='submit' value="upload" />
</form>
controller:
public function index($id=null)
{
$id = $this->input->get('id');
if ($_POST)
{
if ($this->validation())
{
$file = $this->upload_picture();
if ($file['status'] == 'success')
{
echo $this->upload->data('file_name');
}
else
{
echo $file['data'];
echo $file['status'];
$this->session->set_flashdata('alert', alert('error', $file['data']));
}
}
else
{
$this->session->set_flashdata('alert', alert('error', validation_errors()));
}
//redirect($this->agent->referrer());
}
}
private function upload_picture()
{
$config['upload_path'] = './assets/img/page/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['max_size'] = 125000; // 1 GB
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('picture[]'))
{
return array(
'status' => 'error',
'data' => $this->upload->display_errors()
);
}
else
{
$data = $this->upload->data();
$resize['image_library'] = 'gd2';
$resize['source_image'] = './assets/img/page/'.$data['file_name'];
$resize['maintain_ratio'] = TRUE;
// $resize['width'] = 1920;
// $resize['height'] = 1080;
$this->load->library('image_lib', $resize);
$this->image_lib->resize();
return array(
'status' => 'success',
'data' => $this->upload->data()
);
}
}
private function validation()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('picture[0]', 'Picture', 'trim');
$this->form_validation->set_rules('picture[1]', 'Picture', 'trim');
$this->form_validation->set_error_delimiters('', '<br>');
return $this->form_validation->run();
}
result in browser always show error that mean return status to error in upload_picture function, I want to get filename that encrypted and store to database like a4b8a0e070128b0a3dabd9e2931f7ae3.jpg not picture.jpg.

codeigniter upload class doesn't support array file name in this way. So either you have to modify upload class file (not recommended to modify core class file), or you have to modify your codes.
You can name the inputs like this: picture_1, picture_2 etc.
In that case, modify upload_picture() method like this way:
foreach($_FILES as $key=>$val){
if(!$this->upload->do_upload($key)){
$return[$key] = $this->upload->display_errors(); //store this in an array and return at the end. array structure is up to you
}else{
$return[$key] = $this->upload->data(); //store this in an array and return at the end. array structure is up to you
}
}
return $return; //
This way you are uploading files one by one using the loop. However, you have to also modify main method as now it is returning multidimensional array. I've given you just an idea...

Related

How to display disallowed file type error message in case of upload in Codeigniter 3?

I am working on a basic blog application with Codeigniter 3.1.8 and Bootstrap 4.
The posts, of course, have main images. There is a default image if no image is uploaded by the user but, if an image is uploaded, there are only 3 types allowed: jpg, jpeg and png.
Wanting to warn the user in case she/he tries to upload other file formats, I did this in the Posts controller:
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$data['uerrors'] = $this->upload->display_errors();
if ($data['uerrors']) {
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
$post_image = 'default.jpg';
}
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
In the view I have:
<?php foreach ($uerrors as $uerror): ?>
<span><?php echo $uerror; ?></span>
<?php endforeach; ?>
Yet, I get a Undefined variable: uerrors error.
Here is the entire create() method:
public function create() {
// Only logged in users can create posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->get_data();
$data['tagline'] = "Add New Post";
if ($data['categories']) {
foreach ($data['categories'] as &$category) {
$category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
}
}
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('desc', 'Short description', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
// Create slug (from title)
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, null);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$data['uerrors'] = $this->upload->display_errors();
if ($data['uerrors']) {
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
$post_image = 'default.jpg';
}
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->Posts_model->create_post($post_image, $slug);
$this->session->set_flashdata('post_created', 'Your post has been created');
redirect('/');
}
}
Where is my mistake?
Your upload code looks okay, but you need to update these following changes.
Pass data to your 'dashboard/create-post' view as you have passed to your 'partials/header' view. Your 'dashboard/create-post' view is not getting any upload error messages, so it is saying 'Undefined variable: uerrors'. So, your upload code should be like this -
if(!$this->upload->do_upload()){
$data['uerrors'] = $this->upload->display_errors();
if ($data['uerrors']) {
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post', $data);
$this->load->view('partials/footer');
} else {
$post_image = 'default.jpg';
}
} else {
$post_image = $this->upload->data('file_name');
}
As CodeIgniter Documentation says, 'display_errors()' returns string, not array, you don't have to loop through the error. Just echo it on your 'dashboard/create-post' view.
For your convenience, make your upload task in different method so that you can re-use this in update method also. As example -
private function uploadFile(){
if ($_FILES['userfile']['name'] === '') {
return array(
'status' => TRUE,
'message' => 'No file selected.',
'file_name' => 'default.jpg'
);
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile')){
return array(
'status' => FALSE,
'message' => $this->upload->display_errors('<p class="text-danger ">', '</p>'),
'file_name' => ''
);
}else{
return array(
'status' => TRUE,
'message' => 'File uploaded successfully',
'file_name' => $this->upload->data('file_name')
);
}
}
Then your entire create method should look like this -
public function create() {
// Only logged in users can create posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->get_data();
$data['tagline'] = "Add New Post";
if ($data['categories']) {
foreach ($data['categories'] as &$category) {
$category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
}
}
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('desc', 'Short description', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
$upload = $this->uploadFile();
if($upload['status'] === FALSE){
$data['upload_error'] = $upload['message'];
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post', $data);
$this->load->view('partials/footer');
}else{
// Create slug (from title)
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, null);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
$this->Posts_model->create_post($upload['file_name'], $slug);
$this->session->set_flashdata('post_created', 'Your post has been created');
redirect('/');
}
}
}
And finally add this line of code on your 'dashboard/create-post' view file, right after file input button.
<?php if(isset($upload_error)) echo $upload_error; ?>
I think all should work.
There are three things I picked up here
1) not passing $data to the correct view as mentioned before
2) expecting array instead of string on the view ie wrong data type
3) lastly function do_upload() expects parameter string $field. This is missing that's why you are having only the no upload selected error. If this parametre is set codeigniter really throws wrong filetype error. I did this to test
on my view
<form action="http://localhost:8000/welcome/create" method="post" enctype="multipart/form-data">
<input type="file" name="lname" ><br>
<input type="submit" value="Submit">
</form>
then in my controller
if(!$this->upload->do_upload("lname")){
Upload a wrong file type to test this error. You may need to go an extra length to detect the filetype for the actual upload file.
I have succeeded to display the upload errors (if upload is attempted, otherwise a default image is used) by modifying create() this way:
public function create() {
// Only logged in users can create posts
if (!$this->session->userdata('is_logged_in')) {
redirect('login');
}
$data = $this->get_data();
$data['tagline'] = "Add New Post";
if ($data['categories']) {
foreach ($data['categories'] as &$category) {
$category->posts_count = $this->Posts_model->count_posts_in_category($category->id);
}
}
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('desc', 'Short description', 'required');
$this->form_validation->set_rules('body', 'Body', 'required');
$this->form_validation->set_error_delimiters('<p class="error-message">', '</p>');
if($this->form_validation->run() === FALSE){
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
// Create slug (from title)
$slug = url_title(convert_accented_characters($this->input->post('title')), 'dash', TRUE);
$slugcount = $this->Posts_model->slug_count($slug, null);
if ($slugcount > 0) {
$slug = $slug."-".$slugcount;
}
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
// Display upload validation errors
// only if a file is uploaded and there are errors
if (empty($_FILES['userfile']['name'])) {
$errors = [];
}
if (empty($errors)) {
$post_image = 'default.jpg';
} else {
$data['upload_errors'] = $errors;
}
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
if (empty($errors)) {
$this->Posts_model->create_post($post_image, $slug);
$this->session->set_flashdata('post_created', 'Your post has been created');
redirect('/');
} else {
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
}
}
}
In the create-post.php view I have:
<?php if(isset($upload_errors)){
foreach ($upload_errors as $upload_error) {
echo $upload_error;
}
}?>
This error tells you that a variable doesn't exist or was not initialized. Looking at this code
$data['uerrors'] = $this->upload->display_errors();
if ($data['uerrors']) {
I think that you probably have a $uerrors variable somewhere (not shown in this code) which was not initialized. Note that I do not believe that the array index 'uerrors' would cause you trouble in the chunk above, because, first of all you define it and second, if you reference an array item which does not exist, then you will get a different error message from the one quoted in the question.
Your question is a bit vague. Whatever, the only condition in which the variable $uerrors will set is when create() method will execute which I believe would get executed on POST request. Besides, you didn't mention which part of view is this:
<?php foreach ($uerrors as $uerror): ?>
<span><?php echo $uerror; ?> </span>
<?php endforeach; ?>
If it's dashboard/create-post view then try passing $data directly to this view instead of passing it to partials/header
Note: I just checked the codeigniter View/Controller samples and I found it to be a good practice to check variable using isset() function call, so instead of executing foreach loop directly, do this:
<? if (isset($uerrors)): ?>
<? foreach ($uerrors as $uerror): ?>
<span><?= $uerror; ?></span>
<? endforeach; ?>
<? endif; ?>
You need to initialize $data['uerrors'] as null because you are using it on the front end
$data['uerrors'] = '';
or check the value is not empty on the frontend.
Frontend, you can do this as:
<?php if (isset($uerrors) && $uerrors != '') {
foreach ($uerrors as $uerror) {
echo '<span>' . $uerror . '</span>';
}
} ?>
Your controller will be:
$data = array();
// Upload image
$config['upload_path'] = './assets/img/posts';
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = '2048';
$this->load->library('upload', $config);
/*You need to initialize $data['uerrors'] as null because you are using it on front end*/
$data['uerrors'] = '';
if (!$this->upload->do_upload('FilePath')) {
$data['uerrors'] = $this->upload->display_errors();
$this->load->view('partials/header', $data);
$this->load->view('dashboard/create-post');
$this->load->view('partials/footer');
} else {
if (isset($_POST{'your_file'})) {
/*'check your images here that you are receiving from front end'*/
} else {
/*If there is no image, then default image is*/
$post_image = 'default.jpg';
}
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
You can further find useful posts on How to upload image in CodeIgniter?

my image not uploading into database in codeigniter [duplicate]

This question already has answers here:
Multiple files upload in Codeigniter
(5 answers)
Closed 5 years ago.
i am uploading four images from my form but the images are not uploading. I pasted my code below. Please correct me where i done mistake. first i did validation and then i configured the and path. Later i loaded upload library and later given image path for each image.
my Controller Code
public function upro()
{
$this->form_validation->set_rules('pro_name','Product','required');
$this->form_validation->set_rules('pro_image1','Image1','required');
$this->form_validation->set_rules('pro_image2','Image2','required');
$this->form_validation->set_rules('pro_image3','Image3','required');
$this->form_validation->set_rules('pro_image4','Image4','required');
// $today = date('Y-m-d');
if($this->form_validation->run()){
function uploadPic()
{
$config=[
'upload_path' => './uploads',
'allowed_types' => 'jpg|gif|png|jpeg'
];
$this->load->library('upload',$config);
}
$data = $this->input->post();
$today = date('Y-m-d');
$data['pro_date'] = $today;
$info = $this->upload->data();
$image_path = base_url("uploads/".$info['raw_name'].$info['file_ext']);
$data['pro_image1'] = $image_path;
$data['pro_image2'] = $image_path;
$data['pro_image3'] = $image_path;
$data['pro_image4'] = $image_path;
unset($data['submit']);
$this->adata->uproQ($data);
$this->session->set_flashdata('msg','Product uplaod success');
return redirect('admin/products');
}else{
$this->session->set_flashdata('msg','product uplaod failed');
return redirect('admin/apro');
}
}
my model Code
public function uproQ($data)
{
return $this->db->insert('products',$data);
}
my form view Code
<?php echo form_open_multipart('admin/upro');?>
<label><h5>product Name:*</h5></label>
<?php echo form_input(['name'=>'pro_name','class'=>'form-control','placeholder'=>'product Name Here','value'=>set_value('pro_name')]);?>
<?php echo form_upload(['name'=>'pro_image1']);?>
<label><h5>product Image2:*</h5></label>
<?php echo form_upload(['name'=>'pro_image2']);?>
<label><h5>product Image3:*</h5></label>
<?php echo form_upload(['name'=>'pro_image3']);?>
<label><h5>product Image4:*</h5></label>
<?php echo form_upload(['name'=>'pro_image4']);?>
<button type="reset" class="btn btn-warning">Reset</button> <button type="submit" class="btn btn-primary">Submit</button><hr>
<?php form_close();?>
Aside from the method inside the method, and aside from never calling $this->upload->do_upload('name_of_input'), the upload class can only upload one image at a time, you need a for loop for your files array. Also you cannot use form validation for image uploads, form validation only works for $_post fields not $_files fields. I'm surprised this isn't giving you an error that the fields aren't present.
$this->load->library('form_validation');
$this->form_validation->set_rules('pro_name', 'Product', 'required');
$expected_files = array('pro_image1', 'pro_image2', 'pro_image3', 'pro_image4');
//https://stackoverflow.com/questions/12289225/codeigniter-file-upload-required-validation
$i = 1;
foreach ($expected_files as $field_name) {
if (empty($_FILES[$field_name]['name'])) {
$this->form_validation->set_rules($field_name, 'Image' . $i, 'required');
}
$i++;
}
if ($this->form_validation->run()) {
$config = [
'upload_path' => './uploads',
'allowed_types' => 'jpg|gif|png|jpeg',
];
$this->load->library('upload', $config);
$data = array();
foreach ($_FILES as $field_name => $field_values) {
if (!in_array($field_name, $expected_files)) {
continue; // just in case user tries to add more upload fields
}
$this->upload->do_upload($field_name);
$info = $this->upload->data();
$image_path = base_url("uploads/" . $info['raw_name'] . $info['file_ext']);
$data[$field_name] = $image_path;
}
$today = date('Y-m-d');
$data['pro_date'] = $today;
$data['pro_name'] = $this->input->post('pro_name');
$this->adata->uproQ($data);
$this->session->set_flashdata('msg', 'Product upload success!');
return redirect('admin/products');
} else {
$this->session->set_flashdata('msg', validation_errors());
return redirect('admin/apro');
}

codeigniter file upload not uploading file

I am trying to upload the file in codeigniter, but it not uploading, not even if or else are executing, not returning any error, only gives it the output
string(9) "image/png"
here is my code
controller:
$this->load->library('upload');
if($_FILES['categoryIcon']['tmp_name'])
{
$ext=end(explode(".",$_FILES['categoryIcon']['name']));
$filename=date('Ymdhis').rand().".".$ext;
$config['upload_path']=dirname($_SERVER["SCRIPT_FILENAME"])."/assets/images/categories/";
$config['upload_url']=base_url()."assets/images/categories/";
$config['file_name']=$filename;
$config['max_width'] = '2048';
$config['max_height'] = '2048';
$config['allowed_types'] = '*';
$this->upload->initialize($config);
if($this->upload->do_upload('categoryIcon'))
{
$data['categoryIcon']=$filename;
//$response=$this->ecommerce_model->add_new_category($data);
echo "uploaded";
}
else{
echo $this->upload->display_errors();
echo "not uploaded";
}
}
view page
<form action="" method="post" enctype="multipart/form-data" class="practice_form"> <input type="file" name="categoryIcon" id="image" class="form-control" accept="image/*"><input type="submit" value="Save Category" class="btn btn-primary"/>
I have a upload file where you could could do is <input type="file=" name="categoryIcon[]" multiple="multiple"/> and should pick it up you can change do_upload what ever you want.
Also change
This $config['upload_path'] = dirname($_SERVER["SCRIPT_FILENAME"])."/assets/images/categories/";
To This $config['upload_path'] = "./assets/images/categories/"; If your upload folder in on main directory you do not need dirname refer user guide http://www.codeigniter.com/user_guide/libraries/file_uploading.html
echo file data
'$file_info = $this->upload->data();'
'echo $file_info['file_name'];'
Just a example works for multiple codeigniter uploads.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload extends CI_Controller {
function index()
{
$this->get_list();
}
public function get_list() {
$this->load->view('upload_success');
}
function do_upload() {
$this->load->library('form_validation');
// You need to set a form set rules
//$this->form_validation->set_rules('name', 'Banner Name', 'required');
if ($this->form_validation->run()) {
$files = $_FILES;
$file_loop = count($_FILES['categoryIcon']['name']);
for($i= 0; $i < $file_loop; $i++) {
$_FILES['categoryIcon']['name'] = $files['categoryIcon']['name'][$i];
$_FILES['categoryIcon']['type'] = $files['categoryIcon']['type'][$i];
$_FILES['categoryIcon']['tmp_name'] = $files['categoryIcon']['tmp_name'][$i];
$_FILES['categoryIcon']['error'] = $files['categoryIcon']['error'][$i];
$_FILES['categoryIcon']['size'] = $files['categoryIcon']['size'][$i];
$this->upload->initialize($this->file_config());
if (!$this->upload->do_upload()) {
$this->get_form();
} else {
$filename = $files['categoryIcon']['name'][$i];
$this->get_list();
}
} else {
$this->get_form();
}
}
public function get_form() {
$data['error'] = $this->upload->display_errors('<div class="alert alert-info">', '</div>');
$this->load->view('upload_form', $data);
}
private function file_config() {
$config = array();
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = TRUE;
return $config;
}
}

upload image and doc in different folders on form submit in php codeignatior

I have a form with four fileds like contactemail,contactname,category,comments as of now now i have to add image and doc input in a form,using form i have inserted data to db,how to upload image and doc in codeignatior on form submit
images need to upload in image folder and doc in docs folder
Here is my controller
public function form() {
$this->load->helper('form');
$data = $this->login_model->form();
//loading views
load-view-header
load view page
load-view-footer
}
here my model function
public function form() {
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments
);
$this->db->insert('contact', $data);
return $data;
}
Here is an example. This was put together quickly and is completely untested...at best there may be errors and at worst memory has failed me and I totally missed something but may be a useful example. Let me know if it helps?
View:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<!-- your other form fields for email, name, category, comments can go here-->
<input type="file" name="image" size="20" />
<input type="file" name="doc" size="20" />
<br /><br />
<input type="submit" value="Submit" />
</form>
Controller:
function form()
{
$this->load->helper(array('form', 'url'));
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$data['error'] = "";
//it would be good to be using the form validation class but here is a quick and dirty check for the submit
if (isset($_POST['submit']))
{
if ( ! $this->upload->do_upload('image'))
{
$data['error'] = $this->upload->display_errors();
}
else
{
$image_upload_data = $this->upload->data();
}
unset($config);
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'doc|docx|txt';
$config['max_size'] = '2048';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('doc'))
{
$data['error'] .= "<br />".$this->upload->display_errors();
}
else
{
$doc_upload_data = $this->upload->data();
}
if(!empty($data['error']))
{
$this->load->view('form', $data);
}
else
{
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$doc_file = $doc_upload_data['full_path'];
$image_file = $image_upload_data['full_path'];
$form_data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments,
'doc_file' => $doc_file
);
$image_data['image_name'] = $image_file;
$this->login_model->form($form_data,$image_data);
$this->load->view('upload_success', $data);
}
}
else
{
$this->load->view('form', $data);
}
}
Model
public function form($form_data,$image_data) {
$this->db->insert('contact', $image_data);
$image_data['d_fk'] = $this->db->insert_id();
$this->db->insert('images', $image_data);
}

unable to show file error message on the view page in codeigniter

i am trying to show image upload error message using flashdata but the code which i shown below is not working fine. What could be the reason?
Please suggest me a solution to solve this issue.
mycontrollerPage.php
class Booksetups extends CI_Controller
{
function book($book_id = 0)
{
$config = array();
$config['base_url'] = 'http://localhost/thexxr.com/Booksetups/book/pgn/';
$config["total_rows"] = $this->Booksmodel->record_count();
$config['uri_segment'] = 4;
$config['per_page'] = 5;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
//------------not wroking file upload error validation------------------------------------------
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$config['remove_spaces'] = 'TRUE';
$config['file_path'] = 'TRUE';
$config['full_path'] = '/uploads/';
$this->load->library('upload', $config);
$this->upload->do_upload("img1");
$this->upload->do_upload("img2");
//------------------------------------------------------------------------
$this->pagination->initialize($config);
$page = ($this->uri->segment(4)) ? $this->uri->segment(4) : 0;
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('subject_id', 'subject_id','trim|required|min_length[1]|max_length[150]|xss_clean');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('cover_id', 'cover_id','trim|required|min_length[1]|max_length[150]|xss_clean');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('language_id', 'language_id','trim|required|min_length[1]|max_length[150]|xss_clean');
$this->form_validation->set_error_delimiters('<div class="error">', '</div>')->set_rules('edition_id', 'edition_id','trim|required|min_length[1]|max_length[150]|xss_clean');
if(($this->input->post('book_id'))&& ($this->form_validation->run() === TRUE))
{
if( ! $this->upload->do_upload()) //trying to display error
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('error', $error);
redirect(current_url());
}
$this->session->set_flashdata('msg', '1 row(s) affected.');
$this->Booksmodel->entry_update();
redirect(current_url());
}
}
}
Myview.php
<?php echo '<fieldset><legend>'. $formtopic.'</legend>' ?>
<?php echo validation_errors(); ?>
<?php
$message = $this->session->flashdata('msg');
if($message)
{
?>
<div class="success" id="msgdiv"><?php echo $this->session->flashdata('msg'); ?></div>
<?php
}
?>
<?php
$message = $this->session->flashdata('error');
if($message)
{
?>
<?php echo $error;?>
<!-- Here i am getting. Message like "array" why not i am getting the error message instead? -->
<?php
}
?>
I will recommend using form_validation's validation_errors(). Here is how i do it.
Take a look at the library in this answer.
This library has two methods validate_upload (it only checks if file is valid)
and do_upload(must be used only when validate_upload returns true).
There is a file upload library available in Codeigniter Here is the documentation.
Copy the code of my answer and paste it in a file called MY_Upload.php and save this file in application/Code folder.
And now i define a rule like this
$this->form_validation->set_rules('userfile', 'New Image', 'trim|callback_valid_upload');
When the image upload is optional you can wrap it in a condition
if(isset($_FILES['userfile']) AND $_FILES['userfile']['name']!= ''){
$this->form_validation->set_rules('userfile', 'New Image', 'trim|callback_valid_upload');
}
Where userfile is file field of form.
You can see i have called a function in rule callback_valid_upload
Here is method of controller used in callback
public function valid_upload()
{
$this->load->library('upload');
$config['upload_path'] = 'your path here';
$config['allowed_types'] = 'png';
$config['max_size'] = 2048;
$config['max_width'] = 85;
$config['max_height'] = 110;
$this->upload->initialize($config);
if (!$this->upload->validate_upload('userfile'))
{
$this->form_validation->set_message('valid_upload', $this->upload->display_errors());
return FALSE;
}else{
return TRUE;
}
}
This method will check if file we are uploading is valid and will return true on success else false.
When validation is failed load form
View
echo validation_errors();
//blah blah
//<form action="">
// <input type="" />
// <input type="" />
// <input type="" />
//</form>
And if you want to display the messages seperatly
<input type="file" name="userfile" id="" />
<?php echo form_error('userfile')?>
And if validation is successfull upload file now like this.
if($this->form_validation->run())
{
if(isset($_FILES['userfile']) AND $_FILES['userfile']['name'] !='')
{
$this->upload->do_upload('userfile'); // this will upload file
$image_data = $this->upload->data();
$data['image_field_name_of_table'] = $image_data['raw_name'];
}
//other data in $data array here
$id = $this->mymodel->insert($data);
if($id){
$this->session->set_flashdata('notice', ' Successful');
redirect('your url');
}
}else{
//load view here
}
MORE EDITS :
One thing i noticed in your code is a problem
$config = array();
$config['base_url'] = 'http://localhost/thexxr.com/Booksetups/book/pgn/';
$config["total_rows"] = $this->Booksmodel->record_count();
$config['uri_segment'] = 4;
$config['per_page'] = 5;
$config['full_tag_open'] = '<div id="pagination">';
$config['full_tag_close'] = '</div>';
$this->load->library('upload', $config);
$this->upload->do_upload("img1");
unset($config);
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1920';
$config['max_height'] = '1280';
$config['remove_spaces'] = 'TRUE';
$config['file_path'] = 'TRUE';
$config['full_path'] = '/uploads/';
$this->load->library('upload', $config); //load again with new configuration
$this->upload->do_upload("img1");
$this->upload->do_upload("img2");
Here are some of my helper functions to set and show errors in CI
if (!function_exists('set_flash_message'))
{
function set_flash_message($title, $message, $type='success')
{
$CI =& get_instance();
$CI->session->set_flashdata(
'flash_message',
array(
'type' => $type,
'title' => $title,
'text' => $message));
}
}
if (!function_exists('flash_message'))
{
function flash_message()
{
$CI =& get_instance();
$message = $CI->session->flashdata('flash_message');
return $CI->load->view('desktop/flash_message', $message, TRUE);
}
}
You can set message from controller :
set_flash_message('Error', 'Something went wrong', 'error');
and show error from view
<?php echo flash_message(); ?>
As I have said in my comment;
you are getting array because you are setting the flash error message
as an array [$error = array('error' =>
$this->upload->display_errors());], try setting it to just a string
If you look at the function in the source code, it either takes a hash array OR a string.
If an array is passed then it will set the flashdata with the key as the flash message type, message with the value; ignoring the second parameter.
If you pass two arguments as strings it will set the flashdata key with the first string.
So either do;
$this->session->set_flashdata('error', 'something went wrong');
Or
$this->session->set_flashdata(array('error', 'something went wrong'));
Code from the source:
function set_flashdata($newdata = array(), $newval = '')
{
if (is_string($newdata))
{
$newdata = array($newdata => $newval);
}
if (count($newdata) > 0)
{
foreach ($newdata as $key => $val)
{
$flashdata_key = $this->flashdata_key.':new:'.$key;
$this->set_userdata($flashdata_key, $val);
}
}
}

Categories