upload multiple images - php - php

I'm new to PHP, how to make that code support multiple image upload?
I have here 3 button and every one of them can upload single image. I need to make it support multiple upload image. Thank you.
This is all code:
<?php
class Products extends CI_Controller{
function __construct()
{
parent::__construct();
if(!isset($_SESSION['user'])){
redirect('admin/dashboard');
}else{
$user=$_SESSION['user'][0];
if($user->perm==USER){
redirect('admin/denied');
}
}
$this->load->model('product_model');
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|JPG|JPEG|GIF|PNG';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
$this->load->helper('Ultils');
$this->form_validation->set_error_delimiters('<span class="help-inline msg-error" generated="true">', '</span>');
}
function index(){
$page = $this->input->get('page') ? $this->input->get('page') : 0;
$per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 10;
$order = $this->input->get('order') ? $this->input->get('order') : 'DESC';
$config['base_url']= base_url() . 'index.php/admin/products?order='.$order;
$config['per_page']=$per_page;
$data['msg_label']=$this->config->item('msg_label');
$config['total_rows'] = $this->product_model->total(array(), array());
$this->pagination->initialize($config);
$data['list'] = $this->product_model->get("*,products.id as id,products.activated as activated", array(),array(),$page, $per_page, array('products.id' => 'DESC'));
$data['page_link'] = $this->pagination->create_links();
$this->template->write_view('content','backends/products/index',array('data'=>$data));
$this->template->render();
}
public function create(){
$error=null;
$images=array();
$image_path=null;
$insert_id =0;
$thumb=null;
if(isset($_SESSION['user'])){
if(isset($_POST['title'])){
$user=$_SESSION['user'][0];
$this->form_validation->set_rules('title','title', 'trim|required|min_length[5]|max_length[100]|xss_clean');
$this->form_validation->set_rules('price', 'price', 'trim|numeric|xss_clean');
$this->form_validation->set_rules('aim', 'aim', 'trim|required|xss_clean');
$this->form_validation->set_rules('content', 'content', 'trim|required|min_length[5]|max_length[2000]|xss_clean');
$this->form_validation->set_rules('provinces', 'provinces', 'trim|required|xss_clean');
$this->form_validation->set_rules('cities', 'cities', 'trim|required|xss_clean');
$this->form_validation->set_rules('categories', 'categories', 'trim|required|xss_clean');
if($this->form_validation->run()!=false){
$data['title']=preg_replace('/[\r\n]+/', "", $this->input->post('title'));
$data['price']=$this->input->post('price');
$data['aim']=$this->input->post('aim');
$data['content']=preg_replace('/[\r\n]+/', "", htmlspecialchars($this->input->post('content')));
$data['county_id']=$this->input->post('provinces');
$data['categories_id']=$this->input->post('categories');
$data['user_id']=$user->id;
$data['cities_id']=$this->input->post('cities');
$insert_id = $this->product_model->insert($data);
$allowed = array('gif','png' ,'jpg');
$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file']="Your upload file contains invalid allow upload file type";
}
$filename = $_FILES['image1']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload1();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file_1']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file_1']="Your upload file contains invalid allow upload file type";
}
$filename = $_FILES['image2']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(in_array($ext,$allowed)) {
$upload_result=self::upload2();
if($upload_result!=null){
$image_path=$upload_result;
array_push($images, $upload_result);
$this->form_validation->set_rules('image', 'image', 'callback_upload');
}else{
$error['error_upload_file_2']="Can not upload file, please check again";
}
}else{
$error['eror_upload_file_2']="Your upload file contains invalid allow upload file type";
}
if($insert_id!=0){
if($image_path!=null){
$config=array(
"source_image" => 'uploads/'.$image_path, //get original image
"new_image" => "uploads/thumbs", //save as new image //need to create thumbs first
"maintain_ratio" => true,
"width" => 200,
"height" => 200
);
$this->load->library('image_lib',$config);
$this->image_lib->resize();
$image_path= 'uploads/thumbs/'.$image_path;
$this->product_model->update(array('image_path'=>$image_path), array('id'=>$insert_id));
$this->load->model('images_model');
for ($i=0; $i < count($images); $i++) {
$this->images_model->insert(array('path'=>'uploads/'.$images[$i],'product_id'=>$insert_id));
}
}
$this->session->set_flashdata('msg_ok',$this->lang->line('add_successfully'));
redirect('admin/products/create');
}
}
}
; }else{
redirect('admin/dashboard');
}
$this->load->model('county_model');
$data['provinces']=$this->county_model->get();
$this->load->model('categories_model');
$data['categories']=$this->categories_model->get();
$this->template->write_view('content','backends/products/add',array('data'=>$data,'error'=>$error));
$this->template->render();
}
public function upload(){
if(isset($_FILES['image'])){
$filename=$_FILES['image']['name'];
$_FILES['image']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image'))
{
return $_FILES['image']['name'];
}
else
{
return null;
}
}
public function upload1(){
if(isset($_FILES['image1'])){
$filename=$_FILES['image1']['name'];
$_FILES['image1']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image1'))
{
return $_FILES['image1']['name'];
}
else
{
return null;
}
}
public function upload2(){
if(isset($_FILES['image2'])){
$filename=$_FILES['image2']['name'];
$_FILES['image2']['name']=rename_upload_file($filename);
}
if ($this->upload->do_upload('image2'))
{
return $_FILES['image2']['name'];
}
else
{
return null;
}
}
public function check_username_exist_add($name){
$data=$this->product_model->get_by_exact_name($name, 0, 1);
if ($data!=null)
{
$this->form_validation->set_message('check_username_exist_add', 'This name has exist');
return FALSE;
}
else
{
return TRUE;
}
}
public function check_username_exist_edit(){
$id=$this->input->post('id');
$name=$this->input->post('name');
$data=$this->product_model->get_by_name_and_diff_id($id,$name);
if($data!=null) {
$this->form_validation->set_message('check_username_exist_edit', 'This name has exist');
return FALSE;
} else {
return TRUE;
}
}
public function edit_get(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$data=parent::getDataView();
$data['obj']=$this->product_model->get_by_id($id);
$this->blade->render('backends/products/edit',array('data'=>$data));
}
}
public function edit_post(){
if(isset($_POST['id'])){
$id=$_POST['id'];
$name=$_POST['name'];
$data=parent::getDataView();
$this->form_validation->set_rules('name','name', 'trim|required|min_length[5]|max_length[60]|xss_clean|callback_check_username_exist_edit');
if($this->form_validation->run()){
$this->product_model->update(array('name'=>$name),array('id'=>$id));
}
$data['obj']=$this->product_model->get_by_id($id);
$this->blade->render('backends/products/edit',array('data'=>$data));
}
}
public function delete(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$product=$this->product_model->get_by_id($id);
if($product!=null){
$this->load->model('images_model');
$images=$this->images_model->get_by_product_id($id);
foreach ($images as $r) {
try {
unlink($r->path);
$this->images_model->remove_by_id($r->id);
} catch (Exception $e) {
}
}
try {
unlink($product[0]->image_path);
} catch (Exception $e) {
}
}
$this->product_model->remove_by_id($id);
redirect('admin/products');
}
}
public function activate(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
echo $id;
$this->product_model->update(array('activated'=>1),array('id'=>$id));
}
redirect('admin/products');
}
public function lock(){
if(isset($_GET['id'])){
$id=$this->input->get('id');
$this->product_model->update(array('activated'=>0),array('id'=>$id));
}
redirect('admin/products');
}
public function search(){
if(isset($_GET['query'])){
$query=$this->input->get('query');
$data=parent::getDataView();
$page = $this->input->get('page') ? $this->input->get('page') : 0;
$per_page = $this->input->get('per_page') ? $this->input->get('per_page') : 10;
$order = $this->input->get('order') ? $this->input->get('order') : 'DESC';
$config['total_rows'] = $this->product_model->total(array(), array('title'=>$query));
$config['base_url']= base_url() . 'index.php/admin/products/search?order='.$order.'&query='.$query;
$config['per_page']=$per_page;
$data['msg_label']=$this->config->item('msg_label');
$this->pagination->initialize($config);
$data['list'] = $this->product_model->get_by_name($query,$page,$per_page);
$data['page_link'] = $this->pagination->create_links();
$data['search_title']='Result search for "'.$query.'"';
$this->template->write_view('content','backends/products/index',array('data'=>$data));
$this->template->render();
}
}
}
?>

Allow your HTML file input to select many files like <input type="file" name="images[]" multiple> and then loop through the same $_FILES var. Also, don't forget to add the <form> enctype attribute like enctype="multipart/form-data".
$image_files = $_FILES['images']['tmp_name'];
foreach($image_files as $key=>$value){
// write some code to process the information
// this will loop through all the images, no matter how many, so the same code inside these curly braces will be applied to each file/image/whatever.
}

Related

Undefined variable when calling a class method

Getting undefined variable error when calling a static method.
I'm new to coding. please be kind.
I'm trying to dynamically display an event page. It has $title, $price, $location, etc. with a table in the database titled Onlineevent.
I wanted to add a photo gallery to this event page and thought it would be better to have a new table (event_gallery) with columns (id, event_id, and image_name). The event_id is a foreign key from the Onlineevent table.
I'm having no problem calling the Onlineevent data from the database with the method (findy_by_id()). However I cannot call the method that relates to the event_gallery. Please refer to the code.
<?php
$event = Onlineevent::find_by_id($_GET['id']);
if($event){
$event_title = $event->event_title;
$event_type = $event->event_type;
$event_location = $event->event_location;
$event_date = $event->event_date;
$event_start_time = $event->event_start_time;
$event_finish_time = $event->event_finish_time;
$max_participants = $event->max_participants;
$event_price = $event->event_price;
$event_description = $event->event_description;
$event_picture = $event->picture_path();
$event_inclusion_1 = $event->inclusion_1;
$event_inclusion_2 = $event->inclusion_2;
$event_inclusion_3 = $event->inclusion_3;
$event_inclusion_4 = $event->inclusion_4;
$event_inclusion_5 = $event->inclusion_5;
$event_inclusion_6 = $event->inclusion_6;
$event_inclusion_7 = $event->inclusion_7;
$event_inclusion_8 = $event->inclusion_8;
}
$images = Eventgallery::find_by_id($_GET['id']);
if($images){
$image = $images->picture_path();
}
echo $image;
?>
Now I'll share the classes.
class Onlineevent extends Db_object{
protected static $db_table = "onlineevent";
protected static $db_table_fields = array('event_type','event_title','event_picture', 'event_location','event_date','event_start_time','event_finish_time','max_participants','event_price','event_description','event_map','inclusion_1','inclusion_2','inclusion_3','inclusion_4','inclusion_5','inclusion_6','inclusion_7','inclusion_8','inclusion_9','inclusion_10');
public $id;
public $event_type;
public $event_title;
public $event_picture;
public $event_location;
public $event_date;
public $event_start_time;
public $event_finish_time;
public $event_koreans;
public $max_participants;
public $event_foreigners;
public $event_price;
public $event_description;
public $event_map;
public $inclusion_1;
public $inclusion_2;
public $inclusion_3;
public $inclusion_4;
public $inclusion_5;
public $inclusion_6;
public $inclusion_7;
public $inclusion_8;
public $inclusion_9;
public $inclusion_10;
public $tmp_path;
public $upload_directory = "images";
public $errors = array();
public $upload_errors_array = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
This is passing $_FILES['uploaded_file'] as an argument
public function set_file($file) {
if(empty($file) || !$file || !is_array($file)) {
$this->errors[] = "There was no file uploaded here";
return false;
} elseif($file['error'] !=0){
$this->error[] = $this->upload_errors_array[$file['error']];
return false;
} else {
$this->event_picture = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
}
}
public function picture_path(){
return $this->upload_directory.DS.$this->event_picture;
}
public function save(){
if($this->id){
$this->update();
} else {
if(!empty($this->errors)){
return false;
}
if(empty($this->event_picture) || empty($this->tmp_path)){
$this->errors[] = "the file was not available";
return false;
}
$target_path = SITE_ROOT .DS. 'admin'.DS. $this->upload_directory. DS . $this->event_picture;
if(move_uploaded_file($this->tmp_path, $target_path)){
if($this->create()){
unset($this->tmp_path);
return true;
}
} else {
$this->errors[] = "the folder probably does have permission";
return false;
}
}
}
Here is the second class
<?php
class Eventgallery extends Db_object{
protected static $db_table = "event_gallery";
protected static $db_table_fields = array('event_id','image_name');
public $id;
public $event_id;
public $image_name;
public $tmp_path;
public $upload_directory = "images";
public $errors = array();
// public $allowTypes = array('jpg','png','jpeg','gif');
public $upload_errors_array = array(
0 => 'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
This is passing $_FILES['uploaded_file'] as an argument
public function set_file($file) {
if(empty($file) || !$file || !is_array($file)) {
$this->errors[] = "There was no file uploaded here";
return false;
} elseif($file['error'] !=0){
$this->error[] = $this->upload_errors_array[$file['error']];
return false;
} else {
$this->image_name = basename($file['name']);
$this->tmp_path = $file['tmp_name'];
$this->type = $file['type'];
$this->size = $file['size'];
}
}
public function picture_path(){
return $this->upload_directory.DS.$this->image_name;
}
public function save(){
if($this->id){
$this->update();
} else {
if(!empty($this->errors)){
return false;
}
if(empty($this->image_name) || empty($this->tmp_path)){
$this->errors[] = "the file was not available";
return false;
}
$target_path = SITE_ROOT .DS. 'admin'.DS. $this->upload_directory. DS . $this->image_name;
if(move_uploaded_file($this->tmp_path, $target_path)){
if($this->create()){
unset($this->tmp_path);
return true;
}
} else {
$this->errors[] = "the folder probably does have permission";
return false;
}
}
}
I would like to be able to call the static function Eventgallery::find_by_id(); so that I can access the data and then print it out on the event page.
Thank you
When the if statement fails, the $image variable is not defined.
if ($images) {
$image = $images->picture_path();
}
echo $image;
You can solve this by declaring it first.
$image = '';
if ($images) {
$image = $images->picture_path();
}
echo $image;

I want stored image delete when Updated with new image

I am new to codeigniter and I am having problem in edit item image, not that it don't get update as it do but there are too many images in the upload folder directory.
What I want to do is I want the previously stored image to be deleted in the upload directory when I update new image.
Here is my controller:
function edit($shop_id = null){
if ( ! $this->ion_auth->logged_in() OR ! $this->ion_auth->is_admin())
{
redirect('auth', 'refresh');
}
/* Breadcrumbs */
$this->data['breadcrumb'] = $this->breadcrumbs->show();
/* Variables */
$tables = $this->config->item('tables', 'ion_auth');
$this->data['shop_id'] = $shop_id;
/* Get all category */
$this->data['shopInfo'] = $this->shop_model->getShopInfo($shop_id);
//echo "<pre>";print_r( $this->data['shopInfo']);echo "</pre>";exit;
/* Validate form input */
$this->form_validation->set_rules('shop_name', 'Shop Name', 'trim|required');
$this->form_validation->set_rules('shop_latidude', 'Shop Latidude', 'trim|required');
$this->form_validation->set_rules('shop_longitude', 'Shop Longitude', 'trim|required');
if($this->form_validation->run() == true) {
$config['upload_path'] = './assets/uploads/shop/';
//die(var_dump(is_dir($config['upload_path'])));
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
$img_upload = $this->upload->do_upload($img);
$data = $this->upload->data();
$file = array('file_name' => $data['file_name'] );
$data = array('upload_data' => $this->upload->data());
$photo = base_url().'assets/uploads/shop/'.$file['file_name'];
if($img_upload == 1 ) $post_photo = $photo;
else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
$shopInfo = array(
'shop_name' => $this->input->post('shop_name'),
'merchant_id' => $this->input->post('merchant_id'),
'photo' => $post_photo,
'description' => $this->input->post('shop_desc'),
'registered_date'=> date('Y-m-d H:i:s'),
'is_active' => 1,
'shop_location' => $this->input->post('shop_loc'),
'shop_address' => $this->input->post('shop_add'),
'shop_phone' => $this->input->post('shop_ph'),
'shop_latitude' => $this->input->post('shop_latidude'),
'shop_longitude'=> $this->input->post('shop_longitude'),
'open_hour' => $this->input->post('open_hour'),
'close_hour' => $this->input->post('close_hour'),
'remark' => $this->input->post('remark'),
'approved' => $status
);
$this->shop_model->shopUpdate($shop_id, $shopInfo);
redirect(base_url() . 'admin/shop', 'refresh');
} else {
$this->data['message'] = (validation_errors() ? validation_errors() : ($this->ion_auth->errors() ? $this->ion_auth->errors() : $this->session->flashdata('message')));
/* Load Template */
$this->data['merchant'] = $this->merchant_model->getAllMerchants();
$this->template->admin_render("admin/shop/edit", $this->data);
}
}
Here is my Model:
function shopUpdate($shop_id, $shopInfo) {
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
function shopUpdate($shop_id, $shopInfo) {
$q = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
if ($q->num_rows() > 0) {
$imgName = $q->row();
// image path must be './admin/shop'
unlink("./{image pathe}/".$imgName);
}
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
return true;
} else {
return false;
}
} else {
return false;
}
}
you got file name when image got uploaded so get the file name where you are going to update and delete file first. Use unlink to delete file. run update query.
you just need to change in model for updating and deleting at same time.
First, check if new image uploading or not
$new_image = $_FILES['userfile']['name'] ? $_FILES['userfile']['name'] : '';
if($new_image != ''){
$old_image = $this->shop_model->getOlgImage($shop_id);
if(isset($old_image) && file_exists('image-path/photo.jpg')){
unlink('image-path/image');
}
}
Old image is now deleted. Upload new
$config['upload_path'] = './assets/uploads/shop/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$img = "logo";
Give name of your input type file name to $this->upload->do_upload() not variable
No need to add $this->upload->data() twice
if($this->upload->do_upload('userfile')){
$data = $this->upload->data();
$photo = base_url().'assets/uploads/shop/'.$data['file_name'];
$post_photo = $photo;
} else $post_photo = $this->input->post('hidden_photo');
if($this->input->post('status')){
$status = 1;
}else{
$status = 0;
}
Get old image
public function getOldImage($shop_id){
return $this->db->get_where('shop', ['shop_id' => $shop_id])->row()->photo;
}
First, you need to get image name from the database by ID then update record. Once the record is updated then you can delete that image the folder directory.
function shopUpdate($shop_id, $shopInfo) {
//fetch image name from the database by shop_id
$imageName = $this->db->select('photo')->where('shop_id', $shop_id)->get('shop');
$this->db->where('shop_id', $shop_id);
if($shopInfo) {
$query = $this->db->update('shop', $shopInfo);
if ($query) {
//record is updated successfully now delete that image from folder
if ($imageName->num_rows() > 0) {
unlink("./{image pathe}/".$imageName->row());
}
return true;
} else {
return false;
}
} else {
return false;
}
}
unlink()

Codeigniter image upload validation with controller and function

I have a small issue on this code for the to add a product on my system I am using V_add_pro function, when the image upload part is coming I am facing some issues to validate, so that I used a different function to validate through callback, its not working. the main issue is i am saving the image name only to the database, so how to return the image name only?
public function v_add_pro(){
$this->load->model('B_menu');
$data = array('status' => false, 'msg' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules("pro_name", "name needed", "trim|required");
$this->form_validation->set_rules("pro_price", "price needed", "trim|required");
$this->form_validation->set_rules("pro_desc", "description is needed", "trim|required");
$this->form_validation->set_rules("dropzone", "select an image", "trim|required|callback_validate_image");
$this->form_validation->set_rules("pro_cat", "please select a category","callback_check_default|trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if ($this->form_validation->run()) {
$data['status'] = true;
$pro_data = array(
'pname' => $this->input->post('pro_name'),
'pprice' => $this->input->post('pro_price'),
'pdesc' => $this->input->post('pro_desc'),
'pimage' =>$this->input->post('dropzone'),
'catid' => $this->input->post('pro_cat'),
);
$this->B_menu->add($pro_data);
} else {
foreach ($_POST as $key => $value) {
$data['msg'][$key] = form_error($key);
}
}
echo json_encode($data);
}
//to check the selected value for category
function check_default($post_string)
{
return $post_string == '0' ? FALSE : TRUE;
}
//to upload the image to the correct path
public function validate_image() {
$config = array(
'allowed_types'=>'jpg|png|gif',
'upload_path'=> realpath(APPPATH . '../skin/images'),
'max_size'=>1
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('dropzone'))
{
$this->form_validation->set_message('validate_image',$this->upload->display_errors());
} else {
$file_info = $this->upload->data();
$img = $file_info['file_name'];
return $img;
}
}
public function validate_image()
{
/* Start: Image Uploading */
$baseurl = $this->config->base_url();
$profile_photo = "";
$profile_path = '';
$config['upload_path'] = './assets/profile_pictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
if (!empty($_FILES))
{
$this->file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$this->file_name = time() . "." . $this->file_ext;
$config['file_name'] = $this->file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image', FALSE))
{
echo $this->upload->display_errors();
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if ($_FILES['image']['error'] != 4)
{
return false;
}
}
else
{
$profile_photo = $this->file_name;
$profile_path = $baseurl . "assets/profile_pictures";
return $profile_photo;
}
}
/* End: Image Uploading */
To add-ons I am just saving file name as current timestamp thats it. Also return $imagename and also try to echo this
echo $this->upload->display_errors();

Error on uploading CSV File in Codeigniter

Hi I am trying to import an CSV into MYSQL database using A CI Library. But I get this error in Controller that file type is now allowed
Controller:
<?php
class Csv extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('csv_model');
$this->load->library('csvimport');
}
function index() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$this->load->view('csvindex', $data);
}
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
/*END OF FILE*/
The Model :
<?php
class Csv_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_addressbook() {
$query = $this->db->get('addressbook');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
function insert_csv($data) {
$this->db->insert('addressbook', $data);
}
}
/*END OF FILE*/
I am trying to Import A CSV using PHP Codeigniter. Now I am getting an error that
The filetype you are attempting to upload is not allowed.
So as you can see i have kept the allowed file type = csv then also this issue is coming. So please help. Thanks
Instead of changing the mime type you can go with the CALLBACK function
This will add more portability too...
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$this->form_validation->set_rules('uploaded_file','Uploaded file', 'trim|callback_chk_attachment');
if($this->form_validation->run()){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
Call Back function for File Upload validation:
public function chk_attachment() // callback validation for check the attachment extension
{
$file_type = array('.csv');
if(!empty($_FILES['uploaded_file']['name']))
{
$ext = strtolower(strrchr($_FILES['uploaded_file']['name'],"."));
if(in_array($ext,$ext_array))
{
return true;
}
else
{
$this->form_validation->set_message('chk_attachment','Attachment allowed only csv');
return false;
}
}
{
$this->form_validation->set_message('chk_attachment','image field is required');
return false;
}
}

Codeigniter 2.1 controller not found

I have conroller baner, and when I try to run it (run upload function http://localhost/010/baner/upload_img), I got 404 error:
The page you requested was not found
What is wrong here?
The controller:
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Upload_Baner extends CI_Controller {
protected $path_img_upload_folder;
protected $path_img_thumb_upload_folder;
protected $path_url_img_upload_folder;
protected $path_url_img_thumb_upload_folder;
protected $delete_img_url;
function __construct() {
parent::__construct();
$this->setPath_img_upload_folder("public/img/promotions/");
$this->setPath_img_thumb_upload_folder("public/img/promotions/thumbnails/");
$this->setDelete_img_url(base_url() . 'upload_baner/deleteImage/');
$this->setPath_url_img_upload_folder(base_url() . "public/img/promotions/");
$this->setPath_url_img_thumb_upload_folder(base_url() . "public/img/promotions/thumbnails/");
}
public function upload_img() {
//Format the name
$name = $_FILES['userfile']['name'];
$name = strtr($name, 'ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃà áâãäåçèéêëìíîïðòóôõöùúûüýÿ', 'AAAAAACEEEEIIIIOOOOOUUUUYaaaaaaceeeeiiiioooooouuuuyy');
// replace characters other than letters, numbers and . by _
$name = preg_replace('/([^.a-z0-9]+)/i', '_', $name);
//Your upload directory, see CI user guide
$config['upload_path'] = $this->getPath_img_upload_folder();
$config['allowed_types'] = 'gif|jpg|png|JPG|GIF|PNG';
$config['max_size'] = '1000';
$config['file_name'] = $name;
//Load the upload library
$this->load->library('upload', $config);
if ($this->do_upload()) {
//If you want to resize
$config['new_image'] = $this->getPath_img_thumb_upload_folder();
$config['image_library'] = 'gd2';
$config['source_image'] = $this->getPath_img_upload_folder() . $name;
$config['create_thumb'] = FALSE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 193;
$config['height'] = 94;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data = $this->upload->data();
//Get info
$info = new stdClass();
$info->name = $name;
$info->size = $data['file_size'];
$info->type = $data['file_type'];
$info->url = $this->getPath_img_upload_folder() . $name;
$info->thumbnail_url = $this->getPath_img_thumb_upload_folder() . $name; //I set this to original file since I did not create thumbs. change to thumbnail directory if you do = $upload_path_url .'/thumbs' .$name
$info->delete_url = $this->getDelete_img_url() . $name;
$info->delete_type = 'DELETE';
//Return JSON data
if (IS_AJAX) { //this is why we put this in the constants to pass only json data
echo json_encode(array($info));
//this has to be the only the only data returned or you will get an error.
//if you don't give this a json array it will give you a Empty file upload result error
//it you set this without the if(IS_AJAX)...else... you get ERROR:TRUE (my experience anyway)
} else { // so that this will still work if javascript is not enabled
$file_data['upload_data'] = $this->upload->data();
echo json_encode(array($info));
}
} else {
// the display_errors() function wraps error messages in <p> by default and these html chars don't parse in
// default view on the forum so either set them to blank, or decide how you want them to display. null is passed.
$error = array('error' => $this->upload->display_errors('',''));
echo json_encode(array($error));
}
}
public function do_upload() {
if (!$this->upload->do_upload()) {
return false;
} else {
//$data = array('upload_data' => $this->upload->data());
return true;
}
}
//Function Delete image
public function deleteImage() {
//Get the name in the url
$file = $this->uri->segment(3);
$success = unlink($this->getPath_img_upload_folder() . $file);
$success_th = unlink($this->getPath_img_thumb_upload_folder() . $file);
//info to see if it is doing what it is supposed to
$info = new stdClass();
$info->sucess = $success;
$info->path = $this->getPath_url_img_upload_folder() . $file;
$info->file = is_file($this->getPath_img_upload_folder() . $file);
if (IS_AJAX) {//I don't think it matters if this is set but good for error checking in the console/firebug
echo json_encode(array($info));
} else { //here you will need to decide what you want to show for a successful delete
var_dump($file);
}
}
public function get_files() {
$this->get_scan_files();
}
public function get_scan_files() {
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
}
protected function get_file_object($file_name) {
$file_path = $this->getPath_img_upload_folder() . $file_name;
if (is_file($file_path) && $file_name[0] !== '.') {
$file = new stdClass();
$file->name = $file_name;
$file->size = filesize($file_path);
$file->url = $this->getPath_url_img_upload_folder() . rawurlencode($file->name);
$file->thumbnail_url = $this->getPath_url_img_thumb_upload_folder() . rawurlencode($file->name);
//File name in the url to delete
$file->delete_url = $this->getDelete_img_url() . rawurlencode($file->name);
$file->delete_type = 'DELETE';
return $file;
}
return null;
}
protected function get_file_objects() {
return array_values(array_filter(array_map(
array($this, 'get_file_object'), scandir($this->getPath_img_upload_folder())
)));
}
public function getPath_img_upload_folder() {
return $this->path_img_upload_folder;
}
public function setPath_img_upload_folder($path_img_upload_folder) {
$this->path_img_upload_folder = $path_img_upload_folder;
}
public function getPath_img_thumb_upload_folder() {
return $this->path_img_thumb_upload_folder;
}
public function setPath_img_thumb_upload_folder($path_img_thumb_upload_folder) {
$this->path_img_thumb_upload_folder = $path_img_thumb_upload_folder;
}
public function getPath_url_img_upload_folder() {
return $this->path_url_img_upload_folder;
}
public function setPath_url_img_upload_folder($path_url_img_upload_folder) {
$this->path_url_img_upload_folder = $path_url_img_upload_folder;
}
public function getPath_url_img_thumb_upload_folder() {
return $this->path_url_img_thumb_upload_folder;
}
public function setPath_url_img_thumb_upload_folder($path_url_img_thumb_upload_folder) {
$this->path_url_img_thumb_upload_folder = $path_url_img_thumb_upload_folder;
}
public function getDelete_img_url() {
return $this->delete_img_url;
}
public function setDelete_img_url($delete_img_url) {
$this->delete_img_url = $delete_img_url;
}
}
Your controller is named Upload_Baner so unless you have a route defined that maps baner to upload_Baner this won't work. Does this url work?:
http://localhost/010/upload_Baner/upload_img
That is what your current controller will map to without the route.

Categories