Codeigniter Image uploading issue - php

I am working on codeigniter project. All is working on my localhost. Now i have shifted all the things on server. I am also using cloudfare.
the problem is when i try to upload image it shows me blank screen. Following is my controller code.
// Add Data
function add(){
$data['pageTitle']=$this->lang->line('siteTitle');
// Breadcrumbs
$this->breadcrumbs->push('Dashboard','admin/dashboard');
$this->breadcrumbs->push('Category List','admin/category/index');
$this->breadcrumbs->push('Add Category','admin/category/add');
// Load View
// Form Submit
$this->form_validation->set_rules('_cat_title','Title','required|is_unique[pu_project_category.c_title]');
$this->form_validation->set_rules('_cat_slug','Slug','required');
$this->form_validation->set_rules('_cat_desc','Description','required');
if($this->form_validation->run()==TRUE){
if($this->upload->do_upload('_cat_image')){
$image=$this->upload->data();
$image=$image['file_name'];
}else{
$image='No Image';
}
$data['resUpload']=$this->upload->display_errors();
$data['res']=$this->Category_Model->add($image);
}
// Load View
$this->load->view('admin/common/header',$data);
$this->load->view('admin/common/left-sidebar',$data);
$this->load->view('admin/category/add',$data);
$this->load->view('admin/common/footer',$data);
}
Following is configuration code for uploading file,
// Upload Configuration
$config['upload_path'] = './project_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|zip';
$config['max_size'] = '2000';
$this->load->library('upload', $config);
$this->upload->initialize($config);
Please help me to solve this problem and tell me where i doing wrong.

try this
public function add()
{
$this->form_validation->set_rules('_cat_slug','Slug','required');
if($this->form_validation->run() == TRUE)
{
$this->load->model('welcome_model');//change this with your model
//image upload
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'png|gif|jpg|jpeg';
$config['max_size'] = '7000';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('image'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error); //loads the view display.php with error
}
$upload_data=$this->upload->data();
$image=$upload_data['file_name'];
$this->load->view('upload_view');
$data= array(
'_cat_slug' => $this->input->post('_cat_slug'),
'image' => $image
); //loads view display.php with data
$this->welcome_model->registre($data);//change this with your model function name
}
else
{
echo validation_errors();
}
}

Related

Codeigniter Upload function does not work

I am working on codeigniter and during creation of one of the APIs I got the issue. I tried to upload the image on Server as a file, while searching on the web, I got familiar with inbuild upload class in codeigniter. Please have a look at this code. I am sending file from Android using this tutorial.
public function upload_image_post(){
$config['upload_path'] =base_url().'/uploads/';
$config['file_name'] = rand() .'.jpg';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 10000;
$config['remove_spaces'] = TRUE;
$config['encrypt_name'] = TRUE;
// $file = $this->input->post('file');
$this->load->library('upload', $config);
// $this->upload->initialize($config);
$file=$_FILES['uploaded_file'];
// $this->upload->do_upload($file);
if($file){
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'asQ',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is working*/
$res = $this->db->insert('ww_portfolio_images',$content);
}else{
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'not file',
'sp_id'=>'asQaaaaa',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is not working, Thats Obvious*/
$res = $this->db->insert('ww_portfolio_images',$content);
}
// $destinationPath=APPPATH.'public/assets/uploads/ANKO.jpg';
if($this->upload->do_upload('uploaded_file')) {
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'aaaaaaaaaaaaaaaaas',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
/* This is not working*/
$res = $this->db->insert('ww_portfolio_images',$content);
$this->response(['result' =>'Success',] , REST_Controller::HTTP_OK);
// return ($arr_image_info['full_path']);
}
else{
$content=array(
'image_id'=>'IMG'.rand(),
'album_id'=> 'A',
'sp_id'=>'asass',
'image_name'=>'aAA',
'status'=>1,
'tags'=>'s');
$res = $this->db->insert('ww_portfolio_images',$content);
/* This is working*/
$this->response(['result' => 'ERrro'] , REST_Controller::HTTP_OK);
// $this->response(['result' =>'Image error',], 433);
}
}
I can not figure out the problem I am facing here. I am receiving a file but it does not upload.
I have also tried to use $this->upload->do_upload() instead of $this->upload->do_upload('uploaded_file') and this $config['max_size'] = '10000'; instead of this $config['max_size'] = 10000; . Please help. Any help would be greatly appreciated.
Also, when this code run through web panel, it working fine.
Better if you provide some more detail for the type of error or warning that you are observing.
There could be number of reasons.
1) base_url() gives you the public URL. You have to specify the absolute or relative path to your upload folder.
2) (if you are using an Apache Server) Your Apache user don't have the write permission to the upload folder.
3) Folder path doesn't exists.
If the first one doesn't work, please check the rest of the points. Hope this help you.
Regards
Muaaz
Try using FCPATH
$config['upload_path'] = FCPATH . '/uploads/';
Or
$config['upload_path'] = './uploads/';
Then http://www.codeigniter.com/user_guide/libraries/file_uploading.html#the-controller
<?php
class Example extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->helper('form');
}
// Name function what every you want remember to change it on view form.
public function 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('uploaded_file')) {
// Then the success stuff
$upload_data = $this->upload->data();
echo $upload_data['file_name'];
} else {
// Errors
}
}
}
On view I would use the form helper functions form_open_multipart()
<?php echo form_open_multipart('example/upload');?>
<?php echo form_upload('uploaded_file', 'Upload');?>
<?php echo form_close();?>
check your form input in the view
My form view :
<input id="document" type="file" data-browse-label="browse" name="document" data-show-upload="false" data-show-preview="false" class="form-control file" />
other can be
permission issue for the uploads folder
if the folder does not exist you have to create it
And always try to debug the code with logs
document in the do_upload is the name of the input element in my view
if ($_FILES['document']['size'] > 0) {
$this->load->library('upload');
$config['upload_path'] = 'uploads/images';
$config['allowed_types'] = '*';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = false;
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if (!$this->upload->do_upload('document')) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect($_SERVER["HTTP_REFERER"]);
}
$photo = $this->upload->file_name;
}

Codeigniter Upload Image Choice

I have a form including different inputs and file upload input. I want the users if they want to upload images then upload, but if they don't want to upload. Don't give an error.
if($_POST){
$config['upload_path'] = 'images/tmp';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['min_width'] = 480;
$config['min_height'] = 360;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
$error = array('error' => $this->upload->display_errors());
//Sending this $error to view and if a user didnt upload image and just filled
//the other inputs it shows error. but i dont want that.
} else { }
} else {
redirect(site_url());
}
You are on right track. Just delete or comment this line
$error = array('error' => $this->upload->display_errors());
You might be send your $error to view file like below:
$this->load->view('upload_form', $error);
So Don't send your value to view file. Just call your view when image successfully uploaded below:
if ( ! $this->upload->do_upload('userfile') )
{
// $error = array('error' => $this->upload->display_errors());
/*Delete or comment this line. Do your other stuff here if image not uploaded.*/
}else{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
/* This is example. You can do anything on successfully image upload.*/
}
You can refer codeigniter manual https://www.codeigniter.com/userguide3/libraries/file_uploading.html
$config['upload_path'] = 'images/tmp';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['min_width'] = 480;
$config['min_height'] = 360;
$this->load->library('upload', $config);
//$rand_str="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// $filename=md5(str_shuffle($rand_str.mt_rand()));
// $config['file_name']=$filename;
$this->upload->initialize($config);
if ( $this->upload->do_upload('userfile'))
{
//$data = array('upload_data' => $this->upload->data());
// $data["filename"]=$filename;
// $data["ad_id"]=$lid;
// $data["filename"]=$rand_name;
// $this->Ads_model->insert_image($data);
}
I solved my problem changing the Upload class to give no error. I commented the lines including "no selected files".

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 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); }

codeigniter file is not uploading on remote server

this is a code for swf fiel uploading but the problem is it works fine on localhost but not in the remote server.here is my controller
function do_upload()
{
$pid=$this->input->post('Page_id');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'swf';
$config['max_size'] = '1048';
$config['file_name'] =$pid;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
}
else{
$data=array(
'id'=>$pid,
'link'=>base_url()."uploads/",
'file_name'=>$config['file_name']
);
$this->file_upload_model->upload_data($data);
$this->upload_success();
}
}
i have not done anything except just uploading the path and file name to the database in model. see the demo here
Try this
$pid=$this->input->post('Page_id');
$config['file_name'] = $pid;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'swf';
$config['max_size'] = '1048';
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ($this->upload->do_upload())
{
//upload successful
//do something
}
else
{
$this->session->set_flashdata('error',$this->upload->display_errors());
redirect('controller/method');
/*
In the view file you can echo the error like this
echo $this->session->flashdata('error');
*/
}
You have pass the the field name in the do_upload call like this:
$config = array(
'allowed_types' => 'jpg|jpeg|swf |png', // pipe seperated file types
'upload_path' => './uploads/', // should be the root path
'max_size' => '1048',
'file_name' => $pid
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('your_field_name')) {
// like $this->upload->do_upload($pid)
$error = array('error' => $this->upload->display_errors());
} else {
$swf_data = $this->upload->data();
}
Hope it makes sense
it may be due to PHP server version and it's option.
1).go to cpanel account
2).click "select php version", in the software section.
3).tap the "fileinfo" chexbox in the php option and save.
now you can upload file perfectly.

Categories