This is the function which inserts data into the database. but it sends an empty file path and does not sends the image to folder and database also. when I use print_r($this->upload->data()); die; it shows an Empty array.
public function insert_item()
{
if($this->form_validation->run('item') == FALSE)
{
$this->form_validation->set_error_delimiters('<div class="error" style="color:red">','</div>');
return $this->add_item();
}
else
{
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = 3000;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('item_file'))
{
$error = array('error' => $this->upload->display_errors());
}
echo "<pre>";
print_r($this->upload->data($config));die;
}
$table = 'category';
$data['category'] = $this->my_model->select_data($table);
$this->load->view('admin/items/add_item',$data);
}
Please follow:
HTML CODE:
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html>
Controller code
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
public function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
public function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
Reference URL: https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Related
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;
}
}
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);
}
I know that this question has been asked several times, but all the other question I found are different from what I want.
I want to upload the filename and filepath to a table called 'factoryimages'.
What's the best way of doing this?
My controller function:
function do_upload()
{
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('members/header');
$this->load->view('members/upload_form', $error);
$this->load->view('members/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('members/header');
$this->load->view('members/upload_success', $data);
$this->load->view('members/footer');
}
}
I tried this in my model, but it didn't work:
function insert_images()
{
$insert_data = array(
'filename' => $image_data['file_name'],
'fullpath' => $image_data['full_path']
);
$this->db->insert('bedrijfimages', $insert_data);
}
My view:
<?php echo $error;?>
<br/>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" multiple="true" />
<br /><br />
<input type="submit" value="upload" />
</form>
Edit:
I get an server error but i can't see what it is.
My controller function:
function do_upload()
{
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->upload_model->insert_images($this->upload->data());
$this->load->view('members/header');
$this->load->view('members/upload_form', $error);
$this->load->view('members/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('members/header');
$this->load->view('members/upload_success', $data);
$this->load->view('members/footer');
}
}
My model function:
function insert_images($data = array())
{
$data = array(
'filename' => $image_data['file_name'],
'fullpath' => $image_data['full_path']
);
$this->db->insert('bedrijfimages', $data);
}
What could be the problem?
You must pass this data to your insert as array $this->upload->data()
At your Controller you must set when validation is done
else
{
$this->MODELNAME->insert_images($this->upload->data());
$data = array('upload_data' => $this->upload->data());
$this->load->view('members/header');
$this->load->view('members/upload_success', $data);
$this->load->view('members/footer');
}
And at your model:
function insert_images($image_data = array()){
$data = array(
'filename' => $image_data['file_name'],
'fullpath' => $image_data['full_path']
);
$this->db->insert('bedrijfimages', $data);
}
You can check what information is inside this array at CI documentation page: Codeigniter upload library
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);
}
}
}
I am developing a form that allows the user to upload images as well as data.
I have built forms before but am trying to integrate the file uploading class with my previous controller.
Below is the Controller, Model & Form from my View, can anyone help me tie up the missing link? I have searched all over & not found a solution
class Canvas extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$user = $vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($user != 0 && sizeof($_POST)>0) {
// user already set up. Show thank you page
$this->iterate_profile ($vars['user'],false,$_POST);
$this->load->view('upload_form',$vars);
} else {
// user not set, show welcome message
$this->load->view('canvas',$vars);
}
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
function thank_you() {
$this->load->view('thank_you',$vars);
}
function remove() {
$vars = array();
$this->load->library('FacebookConnect');
$facebook=$this->facebookconnect->connect();
$vars['facebook'] = $facebook;
$vars['user'] = $facebook->getUser();
$this->load->model('Users_Model');
if($vars['user'] == 0) {
// user not set, redirect
redirect('/', 'refresh');
} else {
// user already set up. Remove
$this->load->model('Users_Model');
$this->Users_Model->remove($vars['user']);
}
$this->load->view('removed',$vars);
}
protected function iterate_profile ($user,$breadcrumb,$item) {
foreach($item as $key => $value) {
if(is_array($value)) {
$this->iterate_profile($user,$key,$value);
}
else {
if($breadcrumb) {
//echo '[' . $breadcrumb . '_' . $key . ']= ' . $value . ' <br />';
$key = $breadcrumb . '_' . $key;
}
if( ! $this->Users_Model->exists($user,$key)) {
// does not exist in the database, insert it
$this->Users_Model->add($user,$key,$value);
} else {
$this->Users_Model->update($user,$key,$value);
}
}
}
}
Model:
class Users_Model extends CI_Model {
protected $_name = 'users';
function add($id,$key,$value) {
$data = array(
'id' => $id,
'name' => $key,
'value' => $value
);
return $this->db->insert($this->_name, $data);
}
function update($id,$key,$value) {
$data = array(
'value' => $value
);
$this->db->where(array(
'id' => $id,
'name' => $key
));
return $this->db->update($this->_name, $data);
}
function exists($id,$key=null) {
if($key == null) {
$this->db->where(array(
'id' => $id
));
} else {
$this->db->where(array(
'id' => $id,
'name' => $key
));
}
$query = $this->db->get($this->_name);
if($query->num_rows() > 0) {
return true;
}
return false;
}
function remove($id) {
$data = array(
'id' => $id,
);
return $this->db->delete($this->_name, $data);
}
function all() {
$query = $this->db->get($this->_name);
$results = array();
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$results[]=$row;
}
}
return $results;
}
}
Form in view:
<form action="./" method="post" accept-charset="utf-8" enctype="multipart/form-data">
<table>
<tr><td><b class="ara">XXXXXXXX</b> <input id="name" type="text" name="uid" value="" size="30"></td></tr>
<tr><td><b class="ara">XXXXXXXX</b><input id="dob" type="text" name="date_of_birth" value="" size="30"></td></tr>
<tr><td><b class="ara" >XXXXXXXX</b><input id="email" type="text" name="email" value="" size=30></td></tr>
<tr><td><b class="ara">XXXXXXXX</b> <input id="tel" type="text" name="telephone" value="" size="30"></td></tr>
<tr><td><input type="radio" name="device" value="11" checked><b>XXXXXXXX</b></input>
<input type="radio" name="device" value="305"><b>XXXXXXXX</b></input>
<input type="radio" name="device" value="306"><b>XXXXXXXX</b></input></td></tr>
<tr><td><b>XXXXXXXX</b><select name="reason">
<option value="volvo">XXXXXXXX</option>
<option value="saab">XXXXXXXX</option>
<option value="mercedes">XXXXXXXX</option>
<option value="audi">XXXXXXXX</option></select></td></tr>
<tr><td><b>XXXXXXXX</b><select name="game">
<option value="chuzzle">XXXXXXXX</option>
<option value="tetris">XXXXXXXX</option>
<option value="speed">XXXXXXXX</option></select></td></tr>
<tr><td><input type="file" name="userfile" class="upload" size="30"/></td></tr>
<tr><td><span class="ara tandc">XXXXXXXX</span></td><td><input id="checkme" type="checkbox" class="check" name="Check me" value="Submit"/></td></tr>
<tr><td><b><input type="button" class="btn" id="send" name="Add me" value="Submit"/></td></tr>
</table>
</form>
What error are you actually getting? One problem I see at first glance is that the form submits to ./, not do_upload, so that code probably never runs?
From index(), run do_upload() and change it so it returns true/false depending on success. If there was an error, save it to a class variable like this:
class Canvas extends CI_Controller {
private $upload_error = '';
function __construct() {
...
Then in do_upload(), instead of doing:
$error = array('error' => $this->upload->display_errors());
You can do:
$this->upload_error = array('error' => $this->upload->display_errors());
And in index(), if the result of calling do_upload() is false, read the error from $this->upload_error
Overall, your do_upload() method would look like this:
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$this->upload_error = array('error' => $this->upload->display_errors());
return false;
}
else
{
//$data = array('upload_data' => $this->upload->data());
return true;
}
}