Upload image using codeigniter controller - php

public function add_software()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="error-form">',
'</div>');
$this->form_validation->set_rules('name', 'Name',
'required|min_length[4]|max_length[25]');
$this->form_validation->set_rules('desc', 'Description', 'required');
$this->form_validation->set_rules('licence', 'Licence.', 'required');
$this->form_validation->set_rules('platform', 'Platform', 'required');
$this->form_validation->set_rules('developers', 'Developer',
'required');
$this->form_validation->set_rules('link', 'Developer Website',
'required');
$this->form_validation->set_rules('cat', 'Category', 'required');
$this->form_validation->set_rules('logo', 'Software Logo', 'required');
if ($this->form_validation->run() == FALSE) {
$this->load->view('admin/includes/header');
$this->load->view('admin/add_software');
$this->load->view('admin/includes/footer');
} else {
//Setting values for tabel columns
$data['name'] = $this->input->post('name');
$data['description'] = $this->input->post('desc');
$data['licence'] = $this->input->post('licence');
$data['platform'] = $this->input->post('platform');
$data['developers'] = $this->input->post('developers');
$data['link'] = $this->input->post('link');
$data['category'] = $this->input->post('cat');
$data['logo'] = $this->input->post('logo');
/////////////////////////////////
//set preferences
$config = array(
'upload_path' => '' .base_url(). '/assets/img/logo/',
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "4096000",
'max_height' => "1024",
'max_width' => "1024"
);
//load upload class library
$this->load->library('upload', $config);
$this->upload->data();
$this->upload->do_upload();
/////////////////////////////////
//Transfering data to Model
$this->insert_model->form_insert($data);
$data['message'] = 'Data Inserted Successfully';
//Loading View
redirect('admin/view_softwares', 'refresh');
}
}
This is my codeigniter controller function. Using this function, I can add data to the database. But, I am unable to upload image. Even upload_files is enabled in php.ini. I tried resolving this problem all day long, but all in vain.
I have not used enctype in my html form because when I use enctype, I get the below error:
undefined Index filename

Friend i wil give code that i have done for uploading image.This surely work.
You can refer this.Any doubt,please ask,i wil help you
public function uploadImage() {
$this->load->helper(array('form', 'url'));
$config['upload_path'] = 'assets/images/b2bcategory';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '2024';
$config['max_height'] = '1768';
$config['width'] = 75;
$config['height'] = 50;
if (isset($_FILES['catimage']['name'])) {
$filename = "-" . $_FILES['catimage']['name'];
$config['file_name'] = substr(md5(time()), 0, 28) . $filename;
}
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$field_name = "catimage";
$this->load->library('upload', $config);
if ($this->input->post('selsub')) {
if (!$this->upload->do_upload('catimage')) {
//no file uploaded or failed upload
$error = array('error' => $this->upload->display_errors());
} else {
$dat = array('upload_data' => $this->upload->data());
$this->resize($dat['upload_data']['full_path'], $dat['upload_data']['file_name']);
}
$ip = $_SERVER['REMOTE_ADDR'];
if (empty($dat['upload_data']['file_name'])) {
$catimage = '';
} else {
$catimage = $dat['upload_data']['file_name'];
}
$data = array(
'ctg_image' => $catimage,
'ctg_dated' => time()
);
$this->b2bcategory_model->form_insert($data);
}
}

Your path is wrong.
'upload_path' => '' .base_url(). '/assets/img/logo/',
Note: Make sure your upload path "assets folder" is in the main directory out side of
application folder. You also may need to set folder permissions.
Try
'upload_path' => FCPATH . 'assets/img/logo/'
or just
'upload_path' => './assets/img/logo/'
To access file info after upload success preferences
$image_info = $this->upload->data();
echo $image_info['file_name'];
Or Through Model
$this->insert_model->form_insert($data, $image_info = array());

Related

Images not saving to temporary folder only saved to Database

I want uploads to save to upload/images folder in my project directory but it is not. The upload/images folder is empty while the upload saves to database directory
public function addArticleForm(){
//check whether user upload picture
if(!empty($_FILES['image_path']['upload_path'])){
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|';
$config['file_name'] = $_FILES['image_path']['upload_path'];
//load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('image_path')){
$uploadData = $this->upload->data();
$image_path = $uploadData['file_name'];
}else{
$image_path = '';
}
}
Try This for setting up a dynamic function for image upload
public function upload_images($path,$filename){
$config = array(
'upload_path' => $path,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "204800", // 20 mb
);
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload($filename)){
$upload_data = $this->upload->data();
$datas = array('file_name' => $upload_data['file_name'], 'file_size'=>$upload_data['file_size'], 'file_type'=>$upload_data['file_type']);
$file_name = $upload_data['file_name'];
$file_size = $upload_data['file_size'];
$file_type = $upload_data['file_type'];
} else {
$datas = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('error_msg',$datas['error']);
}
return $datas;
}
And use above function in another function, Like
public function Add_Customer_Profiles(){
if($this->session->userdata('userid')!="" || null!==$this->session->userdata('userid')){
$custno = $this->input->post('custno',TRUE);
$fname = $this->input->post('fname',TRUE);
$lname = $this->input->post('lname',TRUE);
$email = $this->input->post('email',TRUE);
$mobile = $this->input->post('mobile',TRUE);
$path = './assets/profile_data/';
$img_name = 'customer_img'; // Your file input name
$file_detail = $this->upload_images($path,$img_name);
if(!isset($file_detail['error'])){
//Your Code here
}
}
public function addArticleForm(){
$config['upload_path'] = "./backend/images/";
$config['allowed_types'] = 'gif|jpeg|png|jpg';
$this->path = './backend/images/';
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('file_name'))
{
$error = array('error'=>$this->upload->display_errors());
}else{
$dataUpload = $this->upload->data();
//echo $dataUpload['file_name'];
}
$data = array(
'name'=>$this->input->post('name'),
'image'=>$dataUpload['file_name'],
'created_by'=>$this->input->post('created_by'));
$insertdata = $this->db->insert('table_name',$data);
}

CodeIgniter Upload Image function not working

I am new to CI and I am learning it through tutorials on Youtube. I am trying to upload image with what I found on tutorial here but unfortunately its not working. Below are the codes please help me.
Controller
public function create() {
$data['title'] = 'Create Post';
$data['desc'] = 'Feel free to create a new post here.';
$data['categories'] = $this->post_model->get_categories();
$this->form_validation->set_rules('title', 'Post Title', 'required');
$this->form_validation->set_rules('desc', 'Post Description', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->upload->initialize($config);
if(!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
}
Model
public function create_post($post_image) {
$slug = url_title($this->input->post('title'));
$data = array(
'post_title' => $this->input->post('title'),
'post_slug' => $slug,
'post_desc' => $this->input->post('desc'),
'post_cat_id' => $this->input->post('catid'),
'post_image' => $post_image
);
return $this->db->insert('posts', $data);
}
View
<?php echo form_open_multipart('posts/create'); ?>
<div class="form-group">
<label>Post Title</label>
<?php echo form_input(['name'=>'title', 'placeholder'=>'Add Title', 'class'=>'form-control', 'value'=>set_value('title')]); ?>
</div>
<div class="form-group">
<label>Select Category</label>
<select name="catid" class="form-control">
<?php foreach($categories as $category): ?>
<option value="<?php echo $category['cat_id']; ?>"><?php echo $category['cat_name']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Post Description</label>
<?php echo form_textarea(['name'=>'desc', 'placeholder'=>'Add Description', 'class'=>'form-control', 'value'=>set_value('desc')]); ?>
</div>
<div class="form-group">
<label>Upload Image</label>
<input type="file" name="userfile" size="20">
</div>
<input type="submit" class="btn btn-primary" value="Add Post">
Now whenever I try to create a post with an image it executes if(!$this->upload->do_upload()){ as TRUE and thus inserts noimage.jpg in database as well as image is not uploaded too. Any help would be appreciated. Thanks.
EDIT
On trying to DEBUG it using print_r($this->upload->data()); die(); I got an empty list of array which means the file is not getting submitted from the form itself on the first place. But why? I don't find any error in the form.
Array
(
[file_name] =>
[file_type] =>
[file_path] => ./assets/images/posts/
[full_path] => ./assets/images/posts/
[raw_name] =>
[orig_name] =>
[client_name] =>
[file_ext] =>
[file_size] =>
[is_image] =>
[image_width] =>
[image_height] =>
[image_type] =>
[image_size_str] =>
)
and print_r($errors) give this error. I am close to solve now I guess.
Array
(
[error] =>
The image you are attempting to upload doesn't fit into the allowed dimensions.
)
SOLUTION
I had to change the max_width and max_height to 0 for unlimited. The image was not being uploaded due to this error.
If you think your code is correct. Have you checked folder permissions?
You have to give permission to folders in order to store images
Forget to load upload library do like this :
$this->load->library('upload', $config);
The whole code (file uploading part) should be like this :
else {
// Upload Image
$config['upload_path'] = FCPATH.'assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload', $config);
if($this->upload->do_upload('userfile'))
{
print_r($this->upload->data());die;
$file_name = $this->upload->data('file_name');
$post_image = $file_name;
}
else
{
$errors = array('error' => $this->upload->display_errors());
print_r($errors);die;
$post_image = 'noimage.jpg';
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
try following changes
$config['upload_path'] = './assets/images/posts'; **to** $config['upload_path'] = getcwd().'/assets/images/posts';
You must remove library upload from autoloading and edit code like this.
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload('userfile')){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}
try this code!
public function create() {
$data['title'] = 'Create Post';
$data['desc'] = 'Feel free to create a new post here.';
$data['categories'] = $this->post_model->get_categories();
$this->form_validation->set_rules('title', 'Post Title', 'required');
$this->form_validation->set_rules('desc', 'Post Description', 'required');
if($this->form_validation->run() == FALSE) {
$this->load->view('templates/header');
$this->load->view('posts/create', $data);
$this->load->view('templates/footer');
} else {
// Upload Image
$config['upload_path'] = './assets/images/posts';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 2048;
$config['max_width'] = 500;
$config['max_height'] = 500;
$this->load->library('upload');
$this->upload->initialize($config);
if(!$this->upload->do_upload('userfile'))
{
$errors = array('error' => $this->upload->display_errors());
$post_image = 'noimage.jpg';
} else {
$data = array('upload_data' => $this->upload->data());
$post_image = $_FILES['userfile']['name'];
}
$this->post_model->create_post($post_image);
return redirect('posts');
}

How to upload a zip files in codeigniter?

I'm trying to upload a zip files but I'm getting some error and I want to display the images inside of it. This is my code this is my code:
Controller
$config['upload_path'] = './img/header/';
$config['allowed_types'] = 'rar|zip|gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('title', 'Name', 'trim|required');
if ($this->form_validation->run() == FALSE || !$this->upload->do_upload('userfile')) {
$this->load->view('plmar/admin/headContent');
} else {
$content = array(
'header_title' => $_POST['title'],
'header_path' => $_POST['userfile'],
'upload_data' => $this->upload->data()
);
$this->adminModel->addContent($content);
redirect('Administrator/headContent');
}
$this->load->view('admin/footer');
just add *
for Ex : $config['allowed_types'] = '*'; and remove this $config['allowed_types'] = 'rar|zip|gif|jpg|png|jpeg';

Thumbnails are not created?

I am trying to create thumbnails original image is been uploaded to upload/large
but not thumbnails are created in upload/thumbs I was using the CodeIgniter Image Manipulation Class and it's not working.Help me to sort out problem
My Controller
var $file_path; //for original image
var $file_path_url; //for thumbnails
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->library('session');
$this->is_login();
$this->load->helper(array('form', 'url'));
$this->load->model('Edit_profile');
//return full path of directory
//Make sure these directory have read and write permission
$this->file_path = realpath(APPPATH . '../upload/large');
$this->file_path_url = realpath(APPPATH.'../upload/thumbs');
// $this->load->model('Insert_article');
}
function upload()
{
//loading image class
$session_data = $this->session->userdata('sessiondata');
$user_id = $session_data['user_id'];
//post image
$img=$this->input->post("filename");
//set preferences
$config['remove_spaces']=TRUE;
$config['encrypt_name'] = TRUE; // for encrypting the name
$config['upload_path'] = LARGEPATH;
$config['allowed_types'] = 'jpg|png|gif';
$config['max_size'] = '78000';
//load moadel ********
$this->load->model('Edit_profile');
//load upload class library
$this->load->library('upload', $config);
//$this->upload->do_upload('filename') will upload selected file to destiny folder
if (!$this->upload->do_upload('filename'))
{
// case - failure
$upload_error = array('error' => $this->upload->display_errors());
$this->load->view('edit_profile', $upload_error);
}
else
{
// case - success
//callback returns an array of data related to the uploaded file like the file name, path, size etc
$upload_data = $this->upload->data();
// call to model function *********
$data['images'] = $this->Edit_profile->insert_new_post($upload_data);
//now creating thumbnails
$config1 = array(
'source_image' => $upload_data['full_path'],
'create_thumb' =>true,
'overwrite' =>false,
'maintain_ratio' =>true,
'new_image' => $this->file_path_url,
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
print_r($config1);
$this->load->library('image_lib');
$this->image_lib->initialize($config1);
$this->image_lib->resize();
//here is the second thumbnail, notice the call for the initialize() function again
//$this->image_lib->initialize($config);
//$this->image_lib->resize();
$data['success_msg'] = '<div class="alert alert-success text-center">Your file <strong>' . '</strong> was successfully uploaded!</div>';
redirect(base_url("Display_profilepic/index"));
}
}
//Model
function insert_new_post($upload_data)
{
$session_data = $this->session->userdata('sessiondata');
$user_id = $session_data['user_id'];
$filePath = ltrim(LARGEPATH.$upload_data['file_name'],'.');
//print_r(LARGEPATH);
$query = "UPDATE `tbl_usrs` set profile_picture='".$filePath."' where user_id='".$user_id."'";
// $this->db->query($query,array($img));
$arg=array ($upload_data);
if($this->db->query($query,$arg)==true)
{
return true; // if added to database
}else {
return false;
}
}
Please update the new_image value by including the filename also.
$config1 = array(
'image_library'=>'gd2',
'source_image' => $upload_data['full_path'],
'create_thumb' =>true,
'overwrite' =>false,
'maintain_ratio' =>true,
'new_image' => $this->file_path_url.'/'.$upload_data['file_name'], //add slash
'maintain_ratio' => true,
'width' => 36,
'height' => 36
);
Try to use the following code
$data = $this->upload->data(); $this->thumb($data);
//Function for creating Thumbnails
function thumb($data) {
$config['image_library'] = 'gd2';
$config['source_image'] = $data['full_path'];
$config['create_thumb'] = TRUE;
// $config['maintain_ratio'] = TRUE;
$config['width'] = 350;
$config['height'] = 250;
$this->load->library('image_lib');
$this->image_lib->initialize($config);
$this->image_lib->resize();
$this->image_lib->clear();
return true;
}

code igniter- how to save image in my database mysql/php

In my page , i have created one form with different fields like name, email,password,etc., now i have to upload the image and store in my database. any one send the code with all fields including image upload file. i have to try in many times, image can't upload in my database.
my controller is
function activity()
{
$this->load->library('form_validation');
//field name,error message, validation rules
$this->form_validation->set_rules('activityid', 'Activity Id', 'trim|required');
$this->form_validation->set_rules('hostid', 'Host Id', 'trim|required');
$this->form_validation->set_rules('activityname', 'Activity Name', 'trim|required');
$this->form_validation->set_rules('date', 'Date', 'trim|required');
$this->form_validation->set_rules('venue', 'Venue', 'trim|required');
$this->form_validation->set_rules('typeofactivity', 'Type of Activity', 'trim|required');
$this->form_validation->set_rules('conductedby', 'Conducted By', 'trim|required');
$config['upload_path'] = './asset/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$w = $this->upload->data();
if($this->form_validation->run()==FALSE)
{
//$this->load->view('signup_form');
$this->activity_reg();
}
else
{
$this->load->model('membership_model');
$query=$this->membership_model->activity();
if($query)
{
$data['main_content']='signup_successful';
$this->load->view('includes/templates',$data);
}
else
{
$this->load->view('activity');
}
}
}
my model is
function activity()
{
$w = $this->upload->data();
$new_member_insert_data= array(
'activityid'=>$this->input->post('activityid'),
'hostid'=>$this->input->post('hostid'),
'activityname'=>$this->input->post('activityname'),
'date'=>$this->input->post('date'),
'venue'=>$this->input->post('venue'),
'typeofactivity'=>$this->input->post('typeofactivity'),
'conductedby'=>$this->input->post('conductedby'),
'image' => $w['file_name']
);
$this->load->database();
$insert=$this->db->insert('activity',$new_member_insert_data);
return $insert;
}
Use file_get_contents() function.
$image = $_FILES['YOUR_INPUT_NAME']['tmp_name'];
$new_member_insert_data= array(
'activityid'=>$this->input->post('activityid'),
'hostid'=>$this->input->post('hostid'),
'activityname'=>$this->input->post('activityname'),
'date'=>$this->input->post('date'),
'venue'=>$this->input->post('venue'),
'typeofactivity'=>$this->input->post('typeofactivity'),
'conductedby'=>$this->input->post('conductedby'),
'image' => file_get_contents( $image )
);

Categories