Upload and view multiple images in the same web page in codeigniter - codeigniter

This image shows what I need to do with codeigniter. I have one page with several div tags. I need to upload images and show them at the same place. But there should be 3 different images and 3 different file locations for these images to save. I tried number of ways. Please anyone with idea help me.
My controller
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Controller extends CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function index(){
$this->load->view('file_view', array(
'error' => ' '
));
}
public function file_view()
{
$this->load->view('file_view', array(
'error' => ' '
));
}
public function do_upload()
{
$config = array(
'upload_path' => "./uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$data = array(
'upload_data' => $this->upload->data()
);
$this->load->view('file_view', $data);
} else {
$error = array(
'error' => $this->upload->display_errors()
);
$this->load->view('file_view', $error);
}
}
public function do_upload2()
{
$config = array(
'upload_path' => "./uploads/index2/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if ($this->upload->do_upload()) {
$data = array(
'upload_data' => $this->upload->data()
);
$this->load->view('file_view', $data);
} else {
$error = array(
'error1' => $this->upload->display_errors()
);
$this->load->view('file_view', $error);
}
}
}
?>
My View
<div id="1">
<?php echo form_open_multipart( 'upload_controller/do_upload');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</div>
<div id="2">
<h3>Your file was successfully uploaded!</h3>
<!-- Uploaded file specification will show up here -->
<ul>
<li>
</li>
<img alt="Your uploaded image" src="<?=base_url(). 'uploads/' . $upload_data['file_name'];?>">
</ul>
</div>
<div id="3">
<?php echo form_open_multipart( 'upload_controller/do_upload2');?>
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
<?php echo "<input type='submit' name='submit' value='upload' /> ";?>
<?php echo "</form>"?>
</div>
<div id="4">
<h3>Your file was successfully uploaded!</h3>
<!-- Uploaded file specification will show up here -->
<ul>
<li>
</li>
<img alt="Your uploaded image" src="<?=base_url(). 'uploads/index2/' . $upload_data['file_name'];?>">
</ul>
<p>
<?php echo anchor('upload_controller/file_view', 'Upload Another File!'); ?>
</p>
</div>

Try This Code:
<form method="post" action="uploader/go" enctype="multipart/form-data">
<input type="file" name="image1" /><br />
<input type="file" name="image2" /><br />
<input type="file" name="image3" /><br />
<input type="file" name="image4" /><br />
<input type="file" name="image5" /><br />
<input type="submit" name="go" value="Upload!!!" />
</form>
Here Controller code:
class Uploader extends Controller {
function go() {
if(isset($_POST['go'])) {
/* Create the config for upload library */
/* (pretty self-explanatory) */
$config['upload_path'] = './assets/upload/'; /* NB! create this dir! */
$config['allowed_types'] = 'gif|jpg|png|bmp|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
/* Load the upload library */
$this->load->library('upload', $config);
/* Create the config for image library */
/* (pretty self-explanatory) */
$configThumb = array();
$configThumb['image_library'] = 'gd2';
$configThumb['source_image'] = '';
$configThumb['create_thumb'] = TRUE;
$configThumb['maintain_ratio'] = TRUE;
/* Set the height and width or thumbs */
/* Do not worry - CI is pretty smart in resizing */
/* It will create the largest thumb that can fit in those dimensions */
/* Thumbs will be saved in same upload dir but with a _thumb suffix */
/* e.g. 'image.jpg' thumb would be called 'image_thumb.jpg' */
$configThumb['width'] = 140;
$configThumb['height'] = 210;
/* Load the image library */
$this->load->library('image_lib');
/* We have 5 files to upload
* If you want more - change the 6 below as needed
*/
for($i = 1; $i < 6; $i++) {
/* Handle the file upload */
$upload = $this->upload->do_upload('image'.$i);
/* File failed to upload - continue */
if($upload === FALSE) continue;
/* Get the data about the file */
$data = $this->upload->data();
$uploadedFiles[$i] = $data;
/* If the file is an image - create a thumbnail */
if($data['is_image'] == 1) {
$configThumb['source_image'] = $data['full_path'];
$this->image_lib->initialize($configThumb);
$this->image_lib->resize();
}
}
}
/* And display the form again */
$this->load->view('upload_form');
}
}

Related

How to insert three images using codeigniter

This is my view file
<div class="form-group">
<label>Select Package Image(Large) </label>
<?= form_input(array('type'=>'file','id'=>'pkg_img','name'=>'pkg_img','class'=>'form-control','multiple'=>'')); ?>
</div>
<div class="form-group">
<label>Select Package Image(Mediam)</label>
<?= form_input(array('type'=>'file','id'=>'pkg_img_md','name'=>'pkg_img_md','class'=>'form-control','multiple'=>'')); ?>
</div>
<div class="form-group">
<label>Select Package Image(Small)</label>
<?= form_input(array('type'=>'file','id'=>'pkg_img_sm','name'=>'pkg_img_sm','class'=>'form-control','multiple'=>'')); ?>
</div>
Use Html helper class
$image_properties = array(
'src' => 'images/picture.jpg',
'alt' => 'Me, demonstrating how to eat 4 slices of pizza at one time',
'class' => 'post_images',
'width' => '200',
'height'=> '200',
'title' => 'That was quite a night',
'rel' => 'lightbox'
);
img($image_properties);
// <img src="http://url/index.php/images/picture.jpg" alt="Me, demonstrating how to eat 4 slices of pizza at one time" class="post_images" width="200" height="200" title="That was quite a night" rel="lightbox" />
Assuming that you just want to resize the same image differently (small, medium) sizes you can use the following code. If that is not what you want to accomplish than you can modify it to your liking:
class Test extends CI_Controller {
public function index() {
$this->load->helper('form');
echo form_open_multipart('/test/upload_image/');
echo form_upload('userfile');
echo form_submit(array('name' => 'add_file', 'value' => 'Add File'));
}
public function upload_image() {
if (!is_dir('./uploads/')) {
mkdir('./uploads/', 0755);
}
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|bmp';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile')) {
// handle this with flash messages & redirect
exit($this->upload->display_errors());
}
$image = $this->upload->data();
$this->load->library('image_lib');
$config = array(); // reset config array
$config['image_library'] = 'gd2';
$config['source_image'] = $image['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = FALSE;
$config['thumb_marker'] = '';
$config_sm['new_image'] = "./uploads/{$image['raw_name']}_sm{$image['file_ext']}";
$config_sm['width'] = 50;
$config_sm['height'] = 50;
$this->image_lib->initialize(array_merge($config, $config_sm));
$this->image_lib->resize();
$this->image_lib->clear();
$config_md['new_image'] = "./uploads/{$image['raw_name']}_md{$image['file_ext']}";
$config_md['width'] = 100;
$config_md['height'] = 100;
$this->image_lib->initialize(array_merge($config, $config_md));
$this->image_lib->resize();
$data = array(
'pkg_img_sm' => $config_sm['new_image'],
'pkg_img_md' => $config_md['new_image'],
'pkg_img' => $image['full_path'],
);
print_r($data);
//$this->db->insert('sometable', $data);
}
}
Will generate an array that looks like:
Array ( [pkg_img_sm] => ./uploads/936174c69e709b4c6d7fb840c4094eba_sm.jpg [pkg_img_md] => ./uploads/936174c69e709b4c6d7fb840c4094eba_md.jpg [pkg_img] => C:/xampp/htdocs/uploads/936174c69e709b4c6d7fb840c4094eba.jpg )

CodeIgniter 3 upload image just reloading the page

I am trying to make an upload form but when I submit it, it just refreshes the form, does not even go back to the designated route and no message is shown. Here is my add() function:
public function add()
{
if ($this->input->post()) {
$data['upload_path'] = './uploads/';
$data['allowed_types'] = 'jpg|png|gif';
$data['max_size'] = '500';
$data['max_width'] = '1024';
$data['max_height'] = '768';
$this->load->library('upload', $data);
if ($this->upload->do_upload('imagem')) {
$image_data = $this->upload->data();
$this->session->set_flashdata('message', 'Imagem \'' . $image_data['file_name'] . '\' adicionada');
} else {
$this->session->set_flashdata('message', 'Erro: ' . $this->upload->display_errors());
}
redirect('/admin/banners', 'refresh');
}
$data['page'] = $this->config->item('admin_template_dir_admin') . '/banners/add';
$data['module'] = 'admin';
$this->load->view($this->_container, $data);
}
The form:
<form action="/admin/banners/adicionar" method="POST" enctype="multipart/form-data">
<div class="form-group">
<small>Imagens de até 1024x768</small>
</div>
<div class="form-group">
<label for="selecionar_imagem">Selecionar Imagem</label>
<input type="file" name="imagem" required/>
</div>
<hr/>
<div class="form-group">
<button class="btn btn-primary pull-right">Adicionar</button>
</div>
</form>
Am I missing something?
I made it. It seems I did have to modify the way I was doing the things. I had to create a separated method upload(), instead of doing that if condition inside of the same method I was rendering the view.
public function add()
{
$data['page'] = $this->config->item('admin_template_dir_admin') . '/banners/add';
$data['module'] = 'admin';
$this->load->view($this->_container, $data);
}
public function upload()
{
$this->load->library('upload', array(
'upload_path' => './uploads/',
'allowed_types' => 'jpg',
'max_size' => '5000',
'overwrite' => true
));
if ($this->upload->do_upload('imagem')) {
$this->session->set_flashdata('message', 'Imagem de Banner adicionada');
} else {
$this->session->set_flashdata('message', 'Erro: ' . $this->upload->display_errors());
}
redirect('/admin/banners', 'refresh');
}
And then in the form, modify the method to /admin/banners/upload.

Not displaying error when using upload multi file in codeigniter 2.0

I'm very new in codeigniter. I have a problem when upload multi file in codeigniter.
My upload form can upload multi files, resize and save them to database, everything is Ok, only one thing is not ok : not display error. Example: maximum file is 2MB, i choose file 3MB, it's not display message "The file you are attempting to upload is larger than the permitted size." The same error when i click button upload but not choose a file. The view will display like a image as link. (i'm not enought reputation to post images)
https://drive.google.com/file/d/0B2zpQIbKaLa6Z2Z6LXFrNXlVRUk/view?usp=sharing
This is my Controller:upload.php
private function _upload_files($field='userfile'){
$files = array();
foreach( $_FILES[$field] as $key => $all )
foreach( $all as $i => $val )
$files[$i][$key] = $val;
$files_uploaded = array();
for ($i=0; $i < count($files); $i++) {
$_FILES[$field] = $files[$i];
if ($this->upload->do_upload($field))
$files_uploaded[$i] = $this->upload->data($files);
else
//$files_uploaded[$i] = null;
$files_uploaded[$i] = $this->upload->display_errors();
}
return $files_uploaded;
}
public function do_upload(){
$data['error']="";
$this->_data['loadPage']="upload/upload_view";
$this->load->model('Mcategorie');
$this->_data["categories"] = $this->Mcategorie->listAllCate();
$this->load->model('Malbum');
$this->_data['albums']=$this->Malbum->listAllAlbum1();
$user_folder = './uploads/'.$this->session->userdata('username');
$thumb_folder = './uploads/'.$this->session->userdata('username').'/thumbnail/';
if(!is_dir($user_folder)){
mkdir($user_folder, 0777);
}
if(is_dir($user_folder)){
if(!is_dir($thumb_folder))
mkdir($thumb_folder,0777);
}
if($this->input->post("ok")){
$config['upload_path'] = $user_folder;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048';
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
$this->load->library("upload",$config);
$this->load->library("image_lib");
if ($_FILES['image_list']) {
$images_upload= $this->_upload_files('image_list');
//echo "<pre>";
//print_r($images_upload);exit;
foreach($images_upload as $data){
$config['image_library'] = 'gd2';
$config['source_image'] = './uploads/'.$this->session->userdata('username').'/'.$data['file_name'];
$config['create_thumb'] = TRUE;
$config['new_image'] = './uploads/'.$this->session->userdata('username').'/thumbnail/'.$data['file_name'];
$config['maintain_ratio'] = FALSE;
$config['width'] = 400;
$config['height'] = 300;
$this->image_lib->initialize($config);
$this->image_lib->resize();
$file = array(
'name' => $data['raw_name'].$data['file_ext'],
'thumb_name' => 'thumb_'.$data['raw_name'].$data['file_ext'],
'date' => date("Y-m-d"),
'userid' => $this->session->userdata('userid'),
'username' => $this->session->userdata('username'),
'description' => $this->input->post("description"),
'roleid' => $this->session->userdata("roleid"),
'public' => $this->input->post("kiet"),
'albumid' => $this->input->post("album"),
'categoryid' => $this->input->post("cat"),
);
$this->Mupload->insert_images($file);
}
redirect(base_url()."default/user/profile","refresh");
}
}
$this->load->view ( $this->_data['path'], $this->_data);
}
This is my view: upload_view.php
<div class="upload container col-xs-12 col-sm-12 col-md-12 col-lg-12">
<div class="panel panel-info">
<div class="panel-heading"><strong>Upload Files</strong> <small>Sao Bac Dau Photo Sharing</small></div>
<div class="panel-body">
<!-- Standar Form -->
<form action="<?php echo base_url()."default/upload/do_upload"?>" method="post" enctype="multipart/form-data">
<div class="col-xs-6 col-sm-6 col-md-6 col-lg-6">
<label> Chọn file ảnh cần upload (jpg, jpeg, gif, png) : </label>
<div class="error col-xs-12 col-sm-12 col-md-12 col-lg-12 clear-css" style="color:#FF0081; font-weight: bold">
<?php if(isset($error)){echo $error; }?>
</div>
<div class="input-group">
<span class="input-group-btn" >
<span class="btn btn-primary btn-file">
Browse … <input type="file" multiple id="image_list" name="image_list[]" accept="image/*" >
</span>
</span>
<input type="text" class="form-control" readonly>
</div>
<input type="submit" name="ok" class="btn btn-md btn-primary" value="Upload Photo" >
</div>
</form>
</div>
</div>
What should i do to display error ? Sorry if my english is so bad. thank in advance for your help.
You will store error in $files_uploaded[$i] = $this->upload->display_errors(); but not use of this to display error so you need to fetch error from this array and display it on view.
Please see below code.
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
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);
}
}
}
?>

How do I get domPDF to display my codeigniter view correctly

I feel there is a small step that I am missing that apparently everyone on the other related questions understands.
I have created a simple CI 2 view, controller and model, shown below:
I have installed dompdf into the helpers folder like so:
applications/helpers/dompdf
applications/helpers/dompdf/dompdf_help.php
What I want to happen is when user clicks the submit button on the view page, send form data to the db, then get a pdf of that filled in form.
Between getting underdefined var errors or nothing at all, except for the data going to db, I can't see what I am missing.
Could some please guide me? What am I not getting here?
View
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>test pdf</title>
</head>
<body>
<?php // Change the css classes to suit your needs
$attributes = array('class' => '', 'id' => '');
echo form_open('quicksubmit', $attributes); ?>
<p>
<label for="title">Title <span class="required">*</span></label>
<?php echo form_error('title'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Mrs' => 'Mrs',
'Miss' => 'Miss',
'Ms' => 'Ms',
'Mr' => 'Mr',
); ?>
<br /><?php echo form_dropdown('title', $options, set_value('title'))?>
</p>
<p>
<label for="first_name">First Name</label>
<?php echo form_error('first_name'); ?>
<br /><input id="first_name" type="text" name="first_name" maxlength="100" value="<?php echo set_value('first_name'); ?>" />
</p>
<p>
<label for="last_name">Last Name <span class="required">*</span></label>
<?php echo form_error('last_name'); ?>
<br /><input id="last_name" type="text" name="last_name" maxlength="100" value="<?php echo set_value('last_name'); ?>" />
</p>
<p>
<label for="branch">Branch</label>
<?php echo form_error('branch'); ?>
<?php // Change the values in this array to populate your dropdown as required ?>
<?php $options = array(
'' => 'Please Select',
'Branch 1' => 'Branch One',
'Branch 2' => 'Branch Two',
); ?>
<br /><?php echo form_dropdown('branch', $options, set_value('branch'))?>
</p>
<p>
<label for="zip">Zip</label>
<?php echo form_error('zip'); ?>
<br /><input id="zip" type="text" name="zip" maxlength="7" value="<?php echo set_value('zip'); ?>" />
</p>
<p>
<?php echo form_submit( 'submit', 'Submit'); ?>
</p>
<?php echo form_close(); ?>
</body>
</html>
Controller
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->model('quicksubmit_model');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$this->pdf($output);
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf()
{
$this->load->helper(array('dompdf', 'file'));
// page info here, db calls, etc.
$html = $this->load->view('quicksubmit_view', $data, true);
pdf_create($html, 'filename');
/*or
$data = pdf_create($html, '', false);
write_file('name', $data);*/
//if you want to write it to disk and/or send it as an attachment
}
}
?>
Model
<?php
class Quicksubmit_model extends CI_Model {
function __construct()
{
parent::__construct();
}
// --------------------------------------------------------------------
/**
* function SaveForm()
*
* insert form data
* #param $form_data - array
* #return Bool - TRUE or FALSE
*/
function SaveForm($form_data)
{
$this->db->insert('quicksubmit', $form_data);
if ($this->db->affected_rows() == '1')
{
return TRUE;
}
return FALSE;
}
}
?>
dompdf_help.php file
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function pdf_create($html, $filename='', $stream=TRUE)
{
require_once("dompdf/dompdf_config.inc.php");
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
if ($stream) {
$dompdf->stream($filename.".pdf");
} else {
return $dompdf->output();
}
}
?>
you were nearly there!
It is probably better to store dompdf in the third_party folder, and it is not a code igniter helper. - see the path i store it in in the constructor. Then it is always available.
Also, it is probably better to do the 'work' of the program in the model, so this includes making PDFs etc.
don't use a ?> at the end of your code.
i modded your code to work, and verified it did work. it simply saves a file named tmp/name.pdf. I am sure you can work out the rest. i did comment out the database loader because that wasn't needed for me to test the code.
see enc.
<?php
class Quicksubmit extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('form_validation');
//$this->load->database();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('file');
$this->load->model('quicksubmit_model');
global $_dompdf_show_warnings;global $_dompdf_debug;global $_DOMPDF_DEBUG_TYPES;global $_dompdf_warnings;$_dompdf_show_warnings = FALSE;
require_once(realpath(APPPATH."third_party/dompdf")."/dompdf_config.inc.php"); // remember that the constant DOMPDF_TEMP_DIR may need to be changed.
spl_autoload_register('DOMPDF_autoload');
}
function index()
{
$this->form_validation->set_rules('title', 'Title', 'required|trim|xss_clean|max_length[50]');
$this->form_validation->set_rules('first_name', 'First Name', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('last_name', 'Last Name', 'required|trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('branch', 'Branch', 'trim|xss_clean|max_length[100]');
$this->form_validation->set_rules('zip', 'Zip', 'trim|xss_clean|is_numeric|max_length[7]');
$this->form_validation->set_error_delimiters('<br /><span class="error">', '</span>');
if ($this->form_validation->run() == FALSE) // validation hasn't been passed
{
$this->load->view('quicksubmit_view');
}
else // passed validation proceed to post success logic
{
// build array for the model
$form_data = array(
'title' => set_value('title'),
'first_name' => set_value('first_name'),
'last_name' => set_value('last_name'),
'branch' => set_value('branch'),
'zip' => set_value('zip')
);
$this->pdf($form_data);
// run insert model to write data to db
if ($this->quicksubmit_model->SaveForm($form_data) == TRUE) // the information has therefore been successfully saved in the db
{
redirect('quicksubmit/success'); // or whatever logic needs to occur
}
else
{
echo 'An error occurred saving your information. Please try again later';
// Or whatever error handling is necessary
}
}
}
function success()
{
redirect(base_url(),'refresh');
/*echo 'this form has been successfully submitted with all validation being passed. All messages or logic here. Please note
sessions have not been used and would need to be added in to suit your app';*/
}
function pdf($data)
{
$dompdf = new DOMPDF();
$html = $this->load->view('quicksubmit_view', $data, true);
$dompdf->set_paper('a4','portrait');
$dompdf->load_html($html);
$dompdf->render();
$pdf = $dompdf->output();
write_file('tmp/name.pdf', $pdf);
}
}

how to create form for multple image upload in codeigniter

i have created form for multiple image upload.but not working that form.only one image uploading..i want multiple images are to be upload to folder and save image name in database..
My View File
<html>
<head>
<title>Product Upload</title>
<style>
#container
{
width:750px;
margin:0 auto;
//border:5px solid #000000;
}
#container form input[type="text"] {
height:30px;
}
</style>
</head>
<body>
<div id="container" align="center">
<form name="product" action="<?php echo base_url;?>admin/login/upload" method="POST" enctype="multipart/form-data" class="form-horizontal">
<table>
<h3>Add New Product</h3>
<tr><td>Categories</td><td><select name="catid"><option>Categories</option>
<?php if(isset($category_details))
{foreach($category_details as $keys=>$values){ ?>
<option value="<?php echo $values['cat_id'];?>"><?php echo $values['cat_name'];?></option>
<?php }
}?>
</select></td></tr>
<tr>
<td>Product Name:</td><td><input type="text" name="pname"></td></tr>
<tr><td><input type="file" multiple="true" name="userfile" size="20" /></td></tr>
<tr><td><br>Product Image:</td><td><br><input type="file" name="pimage[]" id="pimage" multiple></td></tr>
<tr><td><br>Description:</td><td><br><textarea name="pdescription"></textarea></td></tr>
<tr><td><br>Price:</td><td><br><input type="text" name="price"></td></tr>
<tr><td colspan="2" align="center"><br><input type="submit" name="submit" value="ADD" class="btn btn-primary"></td></tr>
</table>
</form>
</div>
</body>
</html>
My Controller File
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* #see http://codeigniter.com/user_guide/general/urls.html
*/
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->load->model('admin/category_model');
$this->load->model('admin/loginauth_model');
$this->load->model('login_model');
$this->load->library('session');
$this->load->helper('url');
$this->load->helper('cookie');
$this->load->library('encrypt');
$this->load->library('image_CRUD');
}
public function index()
{
$this->load->view('admin/login');
}
public function loadproduct()
{
$category_details=$this->category_model->getCategoryDetails();
$outputdata["category_details"]=$category_details;
$this->load->view('admin/product',$outputdata);
}
public function loginAuth()
{
$this->form_validation->set_rules('email','Enter Email','required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('password','Enter your Password','required|trim|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/login');
}
else
{
$username=$_POST['email'];
$password=$_POST['password'];
$user_details=$this->loginauth_model->logincheck($username,$password);
//print_r($checkauth);
if($user_details)
{
if($this->session->userdata('adminusername'))
{
$adminusername=$this->session->userdata('adminusername');
$outputdata['username']=$adminusername;
}
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
$this->load->view('admin/dashboard',$outputdata);
}
}
}
public function category()
{
//$this->load->view('admin/category');
$this->form_validation->set_rules('cat_name','category name','required|trim|max_length[50]|xss_clean');
$this->form_validation->set_rules('cat_desc','category description','required|trim|max_length[50]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/category');
}
else
{
$addcategory=$this->category_model->addcategory($_POST);
if($addcategory)
{
//**************************pending
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
//print_r($outputdata);
$this->load->view('admin/categorylist',$outputdata);
}
}
}
public function categorylist()
{
//echo image_url;
$category_details=$this->category_model->getCategoryDetails();
$outputdata['category_details']=$category_details;
$outputdata['image_url']=image_url;
$this->load->view('admin/categorylist',$outputdata);
$this->load->view('admin/category');
}
public function userdetails()
{
$user_details=$this->login_model->userdetails();
$outputdata['user_details']=$user_details;
$this->load->view('admin/userdetails',$outputdata);
}
public function upload()
{
$productname=$_POST["pname"];
$description=$_POST["pdescription"];
$price=$_POST["price"];
$catid=$_POST["catid"];
$name_array = array();
echo $count = count($_FILES['pimage']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++) {
$_FILES['pimage']['name']=$value['name'][$s];
$_FILES['pimage']['type'] = $value['type'][$s];
$_FILES['pimage']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['pimage']['error'] = $value['error'][$s];
$_FILES['pimage']['size'] = $value['size'][$s];
$config['upload_path'] = FCPATH.'img/product_uploads/original/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|GIF|PNG|JPG|JPEG';
$config['max_size'] = '100';
$config['max_width'] = '150';
$config['max_height'] = '180';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
//$products=$this->category_model->addproduct($catid,$productname,$description,$imagename,$imagesize,$price,$path);
}
$names= implode(',', $name_array);
/* $this->load->database();
$db_data = array('id'=> NULL,
'name'=> $names);
$this->db->insert('testtable',$db_data);
*/ print_r($names);
//echo FCPATH;
//$productname=$_POST["pname"];
// $description=$_POST["pdescription"];
// $price=$_POST["price"];
//$catid=$_POST["catid"];
// $path = FCPATH.'img/product_uploads/original/';
// $valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP","PNG");
// if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
// $imagename = $_FILES['pimage']['name'];
// $imagesize = $_FILES['pimage']['size'];
// list($txt, $ext) = explode(".", $imagename);
//$products=$this->category_model->addproduct($catid,$productname,$description,$imagename,$imagesize,$price,$path);
//print_r($products);
// $tmp = $_FILES['pimage']['tmp_name'];
//if(move_uploaded_file($tmp, $path.$imagename)) {
// $product_details=$this->category_model->getProductDetails();
//print_r($product_details);
//if(isset($products)){
//echo "aa";
// $this->loadproduct();
//}
// }
//else
// {
//echo "Image Upload Failed.";
//}
}
public function logout()
{
$newdata = array(
'adminuser_id' =>'',
'adminusername' =>'',
'adminemail' => '',
'logged_in' => FALSE,
);
$this->session->unset_userdata($newdata);
$this->session->sess_destroy();
$this->index();
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
You can't just add a multiple attrinbute to <input type="file" />, that's not going to work.
You'll have to use a third-party module/plugin, like Uploadify, to get this functionality running.
You could also check this tutorial on how to integrate Uploadify in CodeIgniter (although I can't see anything CodeIgniterish in your code, but you still tagged the question as CI relevant)
a) Instead of writing this <input type="file" multiple="true" name="userfile" size="20" /> write <input type="file" name="userfile[]" size="20" />
b) Inside your controller you can do something like this:
$files = $_FILES;
$count = count($_FILES['userfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($config);
$this->upload->do_upload();
$image_data = $this->upload->data();
}
Use this to open your upload form :
echo form_open_multipart('admin/do_upload');
After put one or more :
<input type="file" name="name" size="20" />
And use a function like that :
public function do_upload() {
$config['upload_path'] = './assets/images/upload/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/images', $error);
} else {
$data = array('upload_data' => $this->upload->data());
}
}

Resources