Multiple File Upload Controls not working in CI - php

In CodeIgniter, I have 4 file upload controls as under:
<?php echo form_open_multipart('uploadimg');?>
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<input type="submit" value="upload" />
<?php echo form_close();?>
Following is my file upload code:
$name1="img1.jpg";
$config1=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name1,
);
$this->load->library('upload',$config1);
if($this->upload->do_upload('image1'))
{
echo "Image 1 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name2="img2.jpg";
$config2=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name2,
);
$this->load->library('upload',$config2);
if($this->upload->do_upload('image2'))
{
echo "Image 2 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name3="img3.jpg";
$config3=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name3,
);
$this->load->library('upload',$config3);
if($this->upload->do_upload('image3'))
{
echo "Image 3 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
$name4="img4.jpg";
$config4=array(
'upload_path'=>$_SERVER['DOCUMENT_ROOT']."/c/uploads/",
'allowed_types'=>"gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite'=>TRUE,
'max_size'=>"500",
'file_name'=>$name4,
);
$this->load->library('upload',$config4);
if($this->upload->do_upload('image4'))
{
echo "Image 4 has been uploaded successfully";
}
else
{
echo $this->upload->display_errors();
}
I am getting the following output:
Image 1 has been uploaded successfullyImage 2 has been uploaded
successfullyImage 3 has been uploaded successfullyImage 4 has been
uploaded successfully
But, in the uploads folder, I am getting only 1 file. Strange thing is that the file that is being shown is of last file upload control, but the name of file is img1., i.e. name of first uploaded file.
Why is this happening? What is the solution?

Set each config using the initialize() method and not when loading the upload library.
Changed:
$this->load->library('upload', $config*);
To:
$this->upload->initialize($config*);
Updated code:
$this->load->library('upload');
$name1 = "img1.jpg";
$config1 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name1
);
$this->upload->initialize($config1);
if ($this->upload->do_upload('image1')) {
echo "Image 1 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name2 = "img2.jpg";
$config2 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name2
);
$this->upload->initialize($config2);
if ($this->upload->do_upload('image2')) {
echo "Image 2 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name3 = "img3.jpg";
$config3 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name3
);
$this->upload->initialize($config3);
if ($this->upload->do_upload('image3')) {
echo "Image 3 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}
$name4 = "img4.jpg";
$config4 = array(
'upload_path' => FCPATH . "uploads/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|JPG|JPEG",
'overwrite' => TRUE,
'max_size' => "500",
'file_name' => $name4
);
$this->upload->initialize($config4);
if ($this->upload->do_upload('image4')) {
echo "Image 4 has been uploaded successfully";
} else {
echo $this->upload->display_errors();
}

You may try this. This is working properly to upload two file
(audio, image) or more file to the database.
Table Name : products
| id | product_name | price | description| product_image | audio_file |
HTML
<form name="addProduct" id="addProduct" method="POST" enctype="multipart/form-data">
<input type="text" name="product_name" placeholder="Product Name">
<input type="text" name="price" placeholder="Product Price">
<textarea id="description" name="description" class="materialize-textarea" placeholder="Description"></textarea>
<input type="file" name="product_image" id="fileImg">
<input type="file" name="audio_file" id="audio_file">
<input type="button" name="addProduct" value="Add Product" class="btn btn-flat btn-add-product">
</form>
Controller
public function addProducts(){
/*Initialization of model*/
$this->load->model("product_model");
/*store data into array*/
$result=array(
"product_name"=>$_POST["product_name"],
"price"=>$_POST["price"],
"description"=>$_POST["description"],
);
$proID = $this->product_model->addProduct($result); //sending data to model for insertion
//Define the file names with blog id with same extension which has been uploaded
$product_image = $proID."_product.".pathinfo($_FILES['product_image']['name'], PATHINFO_EXTENSION);
$product_audio = $proID."_audio.".pathinfo($_FILES['audio_file']['name'], PATHINFO_EXTENSION);
$updateData = array(
"product_image" => $product_image,
"audio_file"=>$product_audio
);
// update the name of the images in the database
$this->product_model->updateProduct($updateData,$proID);
//set configuration for the upload library
/* |===> Image Config <==|*/
$config['upload_path'] = 'html/images/products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
/* |==> Audio Config <==|*/
$config_audio['upload_path'] = 'html/images/products/audios/';
$config_audio['allowed_types'] = 'mp3|mp4';
$config_audio['overwrite'] = TRUE;
$config_audio['encrypt_name'] = FALSE;
$config_audio['remove_spaces'] = TRUE;
//set name in the config file for the feature image
$config['file_name'] = $proID."_product";
$this->load->library('upload', $config); // config first file
$this->upload->do_upload('product_image');
$this->upload->display_errors();
$config_audio['file_name'] = $proID."_audio";
$this->upload->initialize($config_audio); // config seconf file
$this->upload->do_upload('audio_file');
$this->upload->display_errors();
}
Model
/*Add Product*/
public function addProduct($pro_data){
$query=$this->db->insert("products",$pro_data);
$id=$this->db->insert_id();
return $id;
}
/*Update for Multiple File Upload*/
public function updateProduct($result,$up_id){
$this->db->where('id',$up_id);
$this->db->update("products",$result);
}

This is working nicely to my website and i hope it will help you to boost your code.
HTML
<form class="col s12" id='propertyform' enctype="multipart/form-data">
<input type="file" name="image1" />
<input type="file" name="image2" />
<input type="file" name="image3" />
<input type="file" name="image4" />
<a class="waves-effect waves-light btn addproperty">add</a>
</form>
js
$(".addproperty").on("click",function()
{
var baseurl = $("#base_url").val();
var property = new FormData($("#propertyform")[0]);
$.ajax({
url : baseurl+"dropdowns/add_propertyy",
data : property,
type:"POST",
contentType:false,
processData:false,
success:function(res)
{
window.location.reload();
}
});
});
controller
public function add_propertyy()
{
$id = 1;
$images = $id."_image1.".pathinfo($_FILES['image1']['name'], PATHINFO_EXTENSION);
$images1 = $id."_image2.".pathinfo($_FILES['image2']['name'], PATHINFO_EXTENSION);
$images2 = $id."_image3.".pathinfo($_FILES['images3']['name'], PATHINFO_EXTENSION);
$images3 = $id."_image4.".pathinfo($_FILES['image4']['name'], PATHINFO_EXTENSION);
$addimg = array(
"images1" => $images,
"images2" => $images1,
"images3" => $images2,
"images4" => $images3,
);
$this->load->model('property_model');
$this->property_model->add_pro_img($addimg,$id);
$uploadPath = "./html/images/property";
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
$config['file_name'] = $id."_images1";
$this->load->library('upload', $config);
$this->upload->do_upload('images');
$this->upload->display_errors();
$config['file_name'] = $id."_images2";
$this->upload->initialize($config);
$this->upload->do_upload('images2');
$this->upload->display_errors();
$config['file_name'] = $id."_images3";
$this->upload->initialize($config);
$this->upload->do_upload('images3');
$this->upload->display_errors();
$config['file_name'] = $id."_images4";
$this->upload->initialize($config);
$this->upload->do_upload('images4');
$this->upload->display_errors();
}
modal
public function add_pro($data) {
$this->db->insert("property",$data);
$id = $this->db->insert_id();
return $id;
}

Related

How to upload files in two different folders using CodeIgniter3?

How to upload images and videos in two different folders using CodeIgniter 3?
I have done only images. Please guide me through videos. I want to upload image and videos in two different folders.
My Controller, Model and View
class Blog extends CI_Contrller{
public function create_blog(){
// Check Login
if(!$this->session->userdata('logged_in')){
redirect('blogs/login');
}
$data['title'] = 'Create Blog';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if($this->form_validation->run() === FALSE){
$this->load->view('templates/header');
$this->load->view('blog/create_blog', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$path = './assets/uploads/blogs/images';
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 15000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if(!$this->upload->do_upload()){
$this->session->set_flashdata('file_error', $this->upload->display_errors());
$post_image = 'noimage.jpg';
redirect('blog/create_blog');
}else{
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->M_blog->create_blog($post_image);
redirect('blog/view');
}
}
}
Model
// Model Begins here
public function create_blog($post_image){
$slug = url_title($this->input->post('title'));
$data = array(
'title' => $this->input->post('title'),
'slug' => $slug,
'content' => $this->input->post('content'),
'image' => $post_image
);
return $this->db->insert('events', $data);
}
View
// View begins here
<div class="container"><br>
<h2><?= $title ?></h2>
<?php echo form_open_multipart('blog/create_blog'); ?>
<?php echo validation_errors(); ?>
<?php echo $this->session->flashdata('file_error'); ?>
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" name="title"
placeholder="Add Title">
</div>
<div class="form-group">
<label>Body</label>
<textarea class="form-control" id="editor1" name="content"
placeholder="Add Body"></textarea>
</div>
<div class="form-group">
<label>Upload Image</label>
<input type="file" name="userfile" id="userfile" size="20" />
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Try this
class Blog extends CI_Contrller{
function create_blog() {
// Check Login
if (!$this->session->userdata('logged_in')) {
redirect('blogs/login');
}
$data['title'] = 'Create Blog';
$this->form_validation->set_rules('title', 'Title', 'required');
$this->form_validation->set_rules('content', 'Content', 'required');
if ($this->form_validation->run() === FALSE) {
$this->load->view('templates/header');
$this->load->view('blog/create_blog', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$image_ext_arr = array('gif', 'jpg', 'png', 'jpeg');
if (in_array($ext, $image_ext_arr)) {
$path = FCPATH.'assets/uploads/blogs/images';
$allowed_types = 'gif|jpg|png';
} else {
$path = FCPATH.'assets/uploads/blogs/video';
$allowed_types = 'mp4|mp3';
}
$config['upload_path'] = $path;
$config['allowed_types'] = $allowed_types;
$config['max_size'] = 15000;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('file_error', $this->upload->display_errors());
$post_image = 'noimage.jpg';
redirect('blog/create_blog');
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->M_blog->create_blog($post_image);
redirect('blog/view');
}
}
}
Added few line :
$ext = pathinfo($_FILES['userfile']['name'], PATHINFO_EXTENSION); //to find whether is image or video
$ext = strtolower($ext);// some time extension in upper later so converted into small letters
$image_ext_arr = array('gif', 'jpg', 'png', 'jpeg'); //give here all extension of image that you want to upload
if (in_array($ext, $image_ext_arr)) { //if matches means is image
$path = FCPATH.'assets/uploads/blogs/images';
$allowed_types = 'gif|jpg|png';
} else { //else video
$path = FCPATH.'assets/uploads/blogs/video';
$allowed_types = 'mp4|mp3';
}
Note : Better to give absolute path instead of relative path to upload so
$path = FCPATH.'assets/uploads/blogs/video';

filename return empty codeigniter

i have form to upload images in php, when i save the path and name, the name returns empty field in table database here is my code and the value in my database always empty field, please help me
Registration controller
<?php
/**
*
*/
class Registration extends CI_Controller {
function __construct() {
parent::__construct();
//$this->load->library('upload');
$this->load->helper('form');
}
function index() {
$this->load->view('/registration/daftar');
}
function add_user() {
$this->load->model('/daftar/Daftar_Model');
$image_path = APPPATH. 'user_images/';
$config['upload_path'] = $image_path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500';
$config['max_height'] = '450';
$config['max_width'] = '450';
//$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$path = $this->upload->data();
$image_name1 = $path['file_name'];
$image_path1 = $path['file_path'];
//$this->upload->do_upload('foto');
//$photo_data = $this->upload->data();
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'no_telepon' => $this->input->post('no_telepon'),
'alamat' => $this->input->post('alamat'),
'image_path' => $image_path1,
'image_name' => $image_name1
);
$this->db->select('username');
$this->db->where('username', $data['username']);
$result = $this->db->get('user');
if($result->num_rows() > 0) {
echo "Udah ada";
$this->output->set_header('refresh:2; url='.site_url("/registration"));
} else {
if(! $this->upload->do_upload('foto')) {
var_dump($this->upload->display_errors());
//$this->load->view('/registration/daftar', $error);
} else {
//$data1 = array('upload_data' => $this->upload->data());
$this->Daftar_Model->insert($data);
echo "Registrasi Berhasil";
$this->output->set_header('refresh:2; url='.site_url("/login"));
//$this->load->view('/registration/daftar', $data1);
}
}
}
}
this is my form
<html>
<head>
<title>Daftar</title>
<body>
<?php
?>
<h1><center>Daftar</center></h1>
<?php echo form_open_multipart('registration/registration/add_user'); ?>
<center>
Username <br>
<input type="text" name="username"> <br>
Password <br>
<input type="password" name="password"> <br>
Email <br>
<input type="text" name="email"> <br>
No Telepon <br>
<input type="text" name="no_telepon"> <br>
Alamat <br>
<textarea name="alamat" rows="6" cols="23"></textarea> <br>
</form>
Foto
<input type="file" name="foto"><br><br><br>
<input type="submit" name="submit" value="Daftar">
</center>
</form>
</body>
</head>
</html>
Are you check your function add_user()?
I suggested you to check upload status before you can add to database. If your upload code error, they will show you error and then you will know where to fix it. It should be:
if(!$this->upload->do_upload('foto'))
{
// Print the upload error
var_dump($this->upload->display_errors());
}else{
$return = $this->upload->data();
$image_name = $return['file_name'];
// your code add to database
}
Hope this help.

Getting "The filetype you are attempting to upload is not allowed." in codeigniter while uploading video

I am stuck here.. I was trying to upload image and video, image upload working fine but while uploading video getting the error as "The filetype you are attempting to upload is not allowed.". I have tried all the answers but unfortunately couldn't workout. Can someone plz help me. What Am I doing wrong? Thanks.
My View 'home':
<div style="margin-right: 17px;">
<label>Name:</label>
<input type="text" name="name" value="<?php echo set_value('name');?>">
<?php echo form_error('name','<div class="error">','</div>'); ?>
</div>
<div style="padding:20px 20px">
<label>Upload Image</label>
<input type="file" name="photo">
</div>
<div style="padding:5px 5px">
<label>Upload Video</label>
<input type="file" name="video">
</div>
<div style="padding:10px 10px">
<input type="submit" name="sumit" value="Submit">
</div>
</form>
My Controller:
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if(! $this->form_validation->run()){
$data['useradded'] = "";
}
else{
if(isset($_FILES['photo']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/";
$config['allowed_types'] = "jpg|png|gif";
$config['max_size'] = '2048';
$config['max_width'] = '0';
$config['max_height'] = '0';
$new_name = "photo_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('photo')){
$data['error'] = array('error' => $this->upload->display_errors());
$photo_name = "";
}else{
$photo_name = $new_name;
}
}
if(isset($_FILES['video']['tmp_name'])){
$config['upload_path'] = "./uploads/complaints/videos/";
$config['allowed_types'] = "avi|flv|wmv|mpg|mpeg|mp3|mp4";
//$config['allowed_types'] = "video/x-msvideo|image/jpeg|video/mpeg|video/x-ms-wmv";
$config['max_size'] = '0';
$new_name = "video_" . rand();
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
if(! $this->upload->do_upload('video')){
$data['error'] = array('error' => $this->upload->display_errors());
$video_name = "";
}else{
$video_name = $new_name;
}
}
$this->complaints_model->add_complaint($photo_name,$video_name);
$data['useradded'] = "New complaint added Successfully";
}
$this->load->view('home', $data);

CodeIgniter Upload Class Allowed File Types

I'm using Codeigniter Upload Class but I have a problem with allowed file types. I need to allow only pdf files to upload but any kind of file can be upload. Here is my code;
model (muser.php);
function cv_ekle()
{
$config['upload_path'] = 'uploads/cv';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
$this->load->library('upload', $config);
$upload_data = $this->upload->data(); //Returns array of containing all of the data related to the file you uploaded.
$file_name = $upload_data['file_name'];
$data = array
(
'userid' => $this->session->userdata('id'),
'kullanici' => $this->session->userdata('isim'),
'kategori' => $this->input->post('kategori'),
'tarih' => time(),
'dosya' => $file_name
);
if($this->db->insert('cv', $data))
{
return true;
}
else
{
return false;
}
}
controller (cv.php);
function cv_ekle()
{
if($this->muser->cv_ekle())
{
$this->session->set_flashdata('ok', 'CV başarıyla gönderildi!');
redirect('cv');
}
else
{
$this->session->set_flashdata('hata', 'Sadece PDF, Excel ya da Word formatında yükleme yapabilirsiniz!');
redirect('cv');
}
}
view (cv.php);
<form method="post" action="<?php echo site_url('cv/cv_ekle'); ?>" class="login" enctype="multipart/form-data">
<div class="controls">
<label for="email">Dosya: <span class="text-error">*</span></label>
<input type="file" id="pass" class="input-block-level" name="userfile" >
</div>
<div class="controls">
<label for="email">Kategori: <span class="text-error">*</span></label>
<select class="input-block-level" name="kategori">
<?php foreach($kategoriler as $kat) { ?>
<option value="<?php echo $kat['isim']; ?>"><?php echo $kat['isim']; ?></option>
<?php } ?>
</select>
</div>
<div class="controls">
<button type="submit" class="btn btn-primary">CV Yükle</button>
</div>
</form>
Thanks in advance!
function cv_ekle()
{
$config['upload_path'] = 'uploads/cv';
$config['allowed_types'] = 'pdf';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
$this->upload->do_upload();
$upload_data = $this->upload->data(); //Returns array of containing all of the data related to the file you uploaded.
$file_name = $upload_data['file_name'];
$data = array
(
'userid' => $this->session->userdata('id'),
'kullanici' => $this->session->userdata('isim'),
'kategori' => $this->input->post('kategori'),
'tarih' => time(),
'dosya' => $file_name
);
if($this->db->insert('cv', $data))
{
return true;
}
else
{
return false;
}
}

Uploading File failed in Codeigniter

Here is my code and i dont know why its not working i already have mimes.php of csv file
I don't know what is wrong i already use this code in other function its working but in here it's not working.
Controller:
function convert_csv(){
$config['upload_path'] = './files/contracts/';
$config['allowed_types'] = 'pdf|csv';
$config['max_size'] = '4096';
$this->load->library('upload', $config);
$this->upload->display_errors('', '');
if ( !$this->upload->do_upload("csvfile")){
$error = array('error' => $this->upload->display_errors('<span>','</span>'));
$this->session->set_flashdata("upload_message", $error);
} else{
$upload_result = $this->upload->data();
}
}
View:
<?php $form_options = array( 'id' => 'contract_items',
'class' => 'form-horizontal' ); ?>
<?=$this->formbuilder->open( $controller.'/convert_csv/'.$c->id, TRUE, $form_options );?>
<?php echo form_open_multipart('upload/do_upload');?>
Select File To Upload:<br />
<input type="file" name="csvfile" value="csvfile" text="csvfile" />
<br /><br />
<input type="submit" value="Submit" />
function convert_csv(){
$config['upload_path'] = './files/contracts/';
$config['allowed_types'] = 'pdf|csv';
$config['max_size'] = '4096';
$this->load->library('upload', $config);
if ( !$this->upload->do_upload("csvfile")){
echo $this->upload->display_errors();
} else{
$upload_result = $this->upload->data();
var_dump($upload_result);
}
}
Try this. At least you'll find what error going on there

Categories