error in uploading image file - php

i am trying to make a user profile and add a profile picture functionality to it in codeigniter,i simpy copy pasted the file upload code given in the documentation but it is showing error.my view file is
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
my controller is
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
}
public function do_upload()
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 100;
$config['max_width'] = 1024;
$config['max_height'] = 768;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo'not happening';
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
it is showing error over here i mean it is echoing 'not happening',which means it is not uploading.if someone can please help me,it will be great.

Why not you check what is the exact error? I have just updated the code to track exact error what codeigniter is returning.
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo '<pre>';
print_r($this->upload->display_errors());
}

You have loaded the library twice sometimes I found causes issues you have placed one in the constructor and one in the function
Try like below and use $this->upload->initialize($config); in the function and load library in the __constructor.
https://www.codeigniter.com/user_guide/libraries/file_uploading.html#preferences
<?php
class Upload extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
}
public function do_upload()
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 5000;
$config['max_width'] = 0;
$config['max_height'] = 0;
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
echo'not happening';
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
Note no need to close codeigniter controllers and models with ?> as
says in user guide
application
// Where you upload images to
images
system
index.php

Related

how to upload path in codeigniter

I am new to CI. Currently I have the following:
$config['upload_path'] = './uploads/';
I just want to know how to update path in codeignitor. I have tried the below code. Is there something I'm doing wrong?
<?php
defined('BASEPATH')`enter code here` OR exit('No direct script access allowed');
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);
}
}
}
?>
From Your code Your file will be uploaded at uploads folder which is in your root directory. $config['upload_path'] = './uploads/'; this is the place where your uploaded files are stored.
You make an directory uploads there where an application folder is .
If you want your current code.
You'll need a destination folder for your uploaded images. Create a folder at the root of your CodeIgniter installation called uploads and set its file permissions to 777.
By default the upload routine expects the file to come from a form field called userfile.
from file uploading class
Use this library to upload... Its easy to use
http://demo.codesamplez.com/codeigniter/file-upload-demo
View
<form action="" method="POST" enctype="multipart/form-data" >
Select File To Upload:<br />
<input type="file" name="userfile" multiple="multiple" />
<input type="submit" name="submit" value="Upload" class="btn btn-success" />
</form>
{if isset($uploaded_file)}
{foreach from=$uploaded_file key=name item=value}
{$name} : {$value}
<br />
{/foreach}
{/if}
Controller
/**
* the demo for file upload tutorial on codesamplez.com
* #return view
*/
public function file_upload_demo()
{
try
{
if($this->input->post("submit")){
$this->load->library("app/uploader");
$this->uploader->do_upload();
}
return $this->view();
}
catch(Exception $err)
{
log_message("error",$err->getMessage());
return show_error($err->getMessage());
}
}
Component
/**
* Description of uploader
*
* #author Rana
*/
class Uploader {
var $config;
public function __construct() {
$this->ci =& get_instance();
$this->config = array(
'upload_path' => dirname($_SERVER["SCRIPT_FILENAME"])."/files/",
'upload_url' => base_url()."files/",
'allowed_types' => "gif|jpg|png|jpeg|pdf|doc|xml",
'overwrite' => TRUE,
'max_size' => "1000KB",
'max_height' => "768",
'max_width' => "1024"
);
}
public function do_upload(){
$this->remove_dir($this->config["upload_path"], false);
$this->ci->load->library('upload', $this->config);
if($this->ci->upload->do_upload())
{
$this->ci->data['status']->message = "File Uploaded Successfully";
$this->ci->data['status']->success = TRUE;
$this->ci->data["uploaded_file"] = $this->ci->upload->data();
}
else
{
$this->ci->data['status']->message = $this->ci->upload->display_errors();
$this->ci->data['status']->success = FALSE;
}
}
function remove_dir($dir, $DeleteMe) {
if(!$dh = #opendir($dir)) return;
while (false !== ($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
if (!#unlink($dir.'/'.$obj)) $this->remove_dir($dir.'/'.$obj, true);
}
closedir($dh);
if ($DeleteMe){
#rmdir($dir);
}
}
}
$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('image name'))
{
$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);
}

Codeigniter, testing if file uploader has file

I have the following code in my view:
if (isset($stockists)) {
$id = $stockists->ID;
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/'.$id);
}
else {
echo form_open_multipart($system_settings['admin_folder'].'/stockists/form/');
}
<?php echo "<input type='file' name='userfile' size='20' />"; ?>
There's lots of other text input fields in there that are sent to a database on submit. The file up loader is what I'm interested in though.
In my controller function, how can I check if a file exists in the up-loader after submit?
The following retruns false:
$image = ($_FILES['userfile']);
I need to check in a conditional statement if a file exists in the uploader. So for example:
if ($_FILES['userfile']) {
//do
}
But this method does not work.
The super global $_FILES
$_FILES['userfile'] isn't a boolean.
if (strlen($_FILES['userfile']['tmp_name']) > 0) {
// Yes, is uploaded
}
In the array, you've also error:
echo $_FILES['userfile']['error'];
CodeIgniter Approach
CodeIgniter has an upload class that can do the work for you.
CodeIgniter's File Uploading Class permits files to be uploaded. You can set various preferences, restricting the type and size of the files.
Below an example from the CodeIgniter documentation:
<?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);
}
}
}
?>
See for full examples the documentation: CI File Upload Class

Uploading multiple images with codeigniter to a database

My functions upload only one image at a time, when the form is submitted. I can not upload multiple images at once. This is a huge problem because I am building a car-sales website, and people need to upload multiple car images.
My upload.php controller:
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('upload_model');
}
function index()
{
$this->load->view('common/header');
$this->load->view('nav/top_nav');
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
if($this->input->post('upload'))
{
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$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=$this->upload->data();
$this->thumb($data);
$file=array(
'img_name'=>$data['raw_name'],
'thumb_name'=>$data['raw_name'].'_thumb',
'ext'=>$data['file_ext'],
'upload_date'=>time()
);
$this->upload_model->add_image($file);
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
else
{
redirect(site_url('upload'));
}
}
function thumb($data)
{
$config['image_library'] = 'gd2';
$config['source_image'] =$data['full_path'];
$config['create_thumb'] = TRUE;
$config['maintain_ratio'] = TRUE;
$config['width'] = 160;
$config['height'] = 110;
$this->load->library('image_lib', $config);
$this->image_lib->resize();
}
}
My upload_form.php view:
<?php $attributes = array('name' => 'myform');
echo form_open_multipart('/upload/do_upload',$attributes);?>
<input type="file" name="userfile" size="20" />
<input type="submit" value="upload" name="upload" />
<?php echo form_close(); ?>
My upload_model.php Model:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Upload_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
function add_image($data)
{
$this->db->insert('jobs',$data);
}
}
I can't modify the function in a way that allows multiple image upload. I would highly appreciate any kind of guidance or help. Thank you in advance!
#####################
# Uploading multiple#
# Images #
#####################
$files = $_FILES;
$count = count($_FILES['uploadfile']['name']);
for($i=0; $i<$count; $i++)
{
$_FILES['uploadfile']['name']= $files['uploadfile']['name'][$i];
$_FILES['uploadfile']['type']= $files['uploadfile']['type'][$i];
$_FILES['uploadfile']['tmp_name']= $files['uploadfile']['tmp_name'][$i];
$_FILES['uploadfile']['error']= $files['uploadfile']['error'][$i];
$_FILES['uploadfile']['size']= $files['uploadfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());//function defination below
$this->upload->do_upload('uploadfile');
$upload_data = $this->upload->data();
$name_array[] = $upload_data['file_name'];
$fileName = $upload_data['file_name'];
$images[] = $fileName;
}
$fileName = $images;
what's happening in code??
well $_FILE---->it is an associative array of items uploaded to the current script via the POST method.for further look this LINK
it's an automatic variable avaliable within all scopes of script
function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = LARGEPATH; //give the path to upload the image in folder
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '78000';
$config['overwrite'] = FALSE;
return $config;
}
and in your html markup don't don't forget:
Input name must be be defined as an array i.e. name="file[]"
Input element must have multiple="multiple" or just multiple
3.$this->load->library('upload'); //to load library
4.The callback, $this->upload->do_upload() will upload the file selected in the given field name to the destination folder.
5.And the callback $this->upload->data() returns an array of data related to the uploaded file like the file name, path, size etc.

uploading image and text in same mysql table in Codeigniter

I'm trying to upload image and text in a same mysql table in codeigniter but i'm getting a database error like "You must use the "set" method to update an entry."
code on controller
class Addnews extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('addnews', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1040';
$config['max_height'] = '1040';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$newRow = array("news_title" => $this->input->post('news_title'),
"news_description" => $this->input->post('news_description'));
$data = array('upload' => $this->upload->data());
$result = array_merge($newRow, $data);
if ( ! $this->upload->do_upload())
{
$image_data = $this->upload->data();
$newRow['imgpath'] ='assets/images/'.$image_data['file_name'];
$this->load->view('addnews');
}
else
{
$this->load->model("modeladdnews");
$this->modeladdnews->insert_news($result);
$this->load->view('success');
}
}
}
?>
code on model
<?php
class Modeladdnews extends CI_Model {
function insert_news($result)
{
$this->db->insert('news');
}
}
?>
code on view
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('Addnews/do_upload');?>
<?php
echo form_input("news_title", "");
echo form_input("news_description", "");
echo form_upload("userfile");
?>
<br /><br />
<input type="submit" value="submit" />
</form>
</body>
</html>
CI active record class insert method accepts two arguments 1st is table_name and second is array you are not sending the data in insert function see it should be like this.
class Modeladdnews extends CI_Model {
function insert_news($result)
{
$this->db->insert('news',$result);
}
}
your concept is wrong: uploading a file is one thing, updating database is another! Once the image is uploaded (to a directory on your server), you'll want to save the image path and other image data (like date, description, etc.) in your database or execute some image manipulation.
You should have your do_upload controller organized like this:
if ( ! $this->upload->do_upload())
{
//error
$error = $this->upload->display_errors();
$this->load->view('upload_form', $error);
}
else
{
// success!!, file was uploaded
// get data for this file;
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['file_name'];
$data['other_stuff']=$_POST;
// Now update the database
$this->modeladdnews->insert_news($data);
}
$config['upload_path'] = './uploads/images';
$config['allowed_types'] = 'gif|jpg|png|JPG|PNG|GIF';
$config['max_size'] = '20000';
$config['max_width'] = '102400';
$config['max_height'] = '76800';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo "Error While uploading image ! please go back and try again";
} else {
$upload_data = $this->upload->data();
$data['image'] = $upload_data['file_name'];
$data['caption'] = $_POST['caption'];
$this->db->insert('tbl_name', $data); }

trying to upload two images file_path in one column in codeigniter

I am trying to upload two images file_path in one column. In my model i am getting first image path successfully from $filepath but $a is not working i am also confused that $a is getting my second image path or or not
Kindly help me
Thanks in advance.
My Controller
<?php
class upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view("main_temp/header.php");
$this->load->view('post_ad_views', array('error' => ' ' ));
$this->load->view("main_temp/footer.php");
}
// controller
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';
$config['file_name'] = $new_file_name;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view("main_temp/header.php");
$this->load->view('post_ad_views', $error);
$this->load->view("main_temp/footer.php");
}
else
{
// success
$data = array('upload_data' => $this->upload->data());
// a model that deals with your image data (you have to create this)
$this->load->model('submit_ad_model');
$this->submit_ad_model->ad_post();
$this->load->view('upload_success', $data);
}
}
}
?>
MY Model
<?php
class submit_ad_model extends CI_Model
{
function ad_post()
{
$filepath = $this->upload->data()['file_name'];
$a = $this->upload->data()['file_name'];
$this->db->query("insert into ads (ad_pic) values ('$filepath,$a')");
?>
My Views
<input type="file" name="userfile" class="upload image" id="userfile" />
<input type="file" name="userfile2" class="upload image" id="userfile" />
You arent looking to get the second uploaded item, you need to use a loop:
$upload_data = array();
foreach($_FILES as $key => $value){
$this->upload->do_upload($key);
$upload_data[$key] = $this->upload->data($key);
}
$this->submit_ad_model->ad_post($upload_data);

Categories