codeigniter image upload cant grab file name - php

i have try and try and i just cant get my image to upload.
And i cant grab my image name when i try to echo it out :S.
can you see what im doing wrong.
here is my controller:
<?php
//ADMIN PAGE
if (! defined('BASEPATH')) exit('No direct script access');
class News extends CI_Controller {
//Write post when logged in as admin
function write()
{
//insert image
$config['upload_path'] = APPPATH .'/archive/img/news/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('newsImage');
$file_data = $this->upload->data();
$newsData = array(
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'content' => $this->input->post('content'),
'creater' => $this->session->userdata('username'),
'ip' => $this->session->userdata('ip'),
'imgPath' => $file_data['file_name']
);
echo "<pre>";
//print_r( $this->upload->data());
//print_r($file_data);
//print_r($_FILES);
//print_r($this->input->post());
print_r($newsData);
echo "</pre>";
$this->load->model('admin/news_model');
$this->news_model->insertNews($newsData);
$data['main_content'] = 'admin/write_view';
$this->load->view('template', $data);
}
}
And my view file where i upload my image
<div id="inputStyle">
<?php
echo form_open_multipart('admin/news/write');
echo form_input('headline', 'overskrift');
echo form_upload('newsImage');
echo form_textarea('description', 'indhold');
echo form_textarea('content', 'content');
echo form_submit('create', 'Opret nyhed');
echo form_close();
?>
</div><!-- inputStyle -->

I have edited your code. It may be work for you. If your folder is in root folder of application then no need to use APPPATH. I have also edited this in your code. Try this.
//Write post when logged in as admin
function write()
{
//insert image
$config['upload_path'] = 'archive/img/news/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = '9000';
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
$this->upload->do_upload('newsImage');
$file_data = $this->upload->data();
$newsData = array(
'headline' => $this->input->post('headline'),
'description' => $this->input->post('description'),
'content' => $this->input->post('content'),
'creater' => $this->session->userdata('username'),
'ip' => $this->session->userdata('ip'),
'imgPath' => $_FILES['newsImage']['name']
);
echo "<pre>";
//print_r( $this->upload->data());
//print_r($file_data);
//print_r($_FILES);
//print_r($this->input->post());
print_r($newsData);
echo "</pre>";
$this->load->model('admin/news_model');
$this->news_model->insertNews($newsData);
$data['main_content'] = 'admin/write_view';
$this->load->view('template', $data);
}

Related

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 update table with new image data using codeigniter

I have a form to upload image-path and other image-data. This works well when I choose to upload a new image.
How can I prevent that my image-path is set to blank if I submit my form without choosing a new image?
here is my controller:
function updatewaterpurifier($id)
{
$name=$this->input->post('name');
$this->load->model('user');
//$name = $this->input->post('name');
if($this->input->post('submit'))
{
//Check whether user upload picture
if(!empty($_FILES['picture']['name'])){
$new_file_name = $this->input->post('name');
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$config['file_name'] = $new_file_name;
$config['max_size'] = 2048;
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
//Prepare array of user data
$userData = array(
'product_brand'=> $this->input->post('brand'),
'product_name' => $this->input->post('name'),
'product_price' => $this->input->post('price'),
'product_techno' => $this->input->post('technology'),
'product_des' => $this->input->post('description'),
'product_image' => $picture
);
$this->db->where('id', $id);
$this->db->update('products', $userData);
//Pass user data to model
//Storing insertion status message.
}
//Form for adding user data
$this->load->model('user');
$this->data['h']= $this->user->editpurifier($id);
$this->load->view('editwaterpurifier', $this->data, FALSE);
}
if you are updating your table without previous image upload, your variable $picture=''. Use that to unset product_image from the array $userData():
$userData = array(
'product_brand'=> $this->input->post('brand'),
'product_name' => $this->input->post('name'),
'product_price' => $this->input->post('price'),
'product_techno' => $this->input->post('technology'),
'product_des' => $this->input->post('description'),
'product_image' => $picture
);
if ($picture==''){
unset($userData['product_image']);
}
This removes product_image from the array and won't updatinge the image path as blank.
In controller
function updatewaterpurifier($id)
{
$this->load->model('user');
if($this->input->post('submit'))
{
//Prepare array of user data
$userData = array(
'product_brand'=> $this->input->post('brand'),
'product_name' => $this->input->post('name'),
'product_price' => $this->input->post('price'),
'product_techno' => $this->input->post('technology'),
'product_des' => $this->input->post('description')
);
$name=$this->input->post('name');
//Check whether user upload picture
if(!empty($_FILES['picture']['name']))
{
$new_file_name = $this->input->post('name');
$config['upload_path'] = 'uploads/images/';
$config['allowed_types'] = 'jpg|jpeg|png|gif|pdf';
$config['file_name'] = $new_file_name;
$config['max_size'] = 2048;
//Load upload library and initialize configuration
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('picture'))
{
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
$userData['product_image']=$picture;
}
}
//Pass user data to model
$this->user->update_purifier($id,$userData);
}
//Form for adding user data
$this->data['h']= $this->user->editpurifier($id);
$this->load->view('editwaterpurifier', $this->data, FALSE);
}
Model
public function update_purifier($id,$userData)
{
$this->db->where('id', $id);
$this->db->update('products', $userData);
}
check product image name contain extention . if not add
$ext1 = explode('.',$_FILES['picture']['name']);
$ext2 = array_reverse($ext1);
$extention = strtolower($ext2[0]);
$config['file_name'] = $new_file_name.'.'.$extention;

Photo upload, Crop and Save using Codeigniter

We are working on a social network project based on CI framework. I searched on the web but got confused. How to upload photo, allow user to crop the photo and save it using database so that it could be retrieved at the time of call? I'm using this for profile picture.
On view:
<?php echo form_open_multipart ('index.php/Main/do_upload'); ?>
<table class="table">
<tr>
<td>Title</td>
<td><?php echo form_input('title'); ?></td>
</tr>
<tr>
<td>Image</td>
<td><?php echo form_upload('userfile'); ?></td>
</tr>
<tr>
<td></td>
<td><?php echo form_submit('submit', 'Save', 'class="btn btn-primary"'); ?></td>
<?php echo form_close(); ?>
</tr>
</table>
On controller:
public 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('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('Material_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
Use Bluimp Multiple fileupload (https://blueimp.github.io/jQuery-File-Upload) and Croppr (https://fengyuanchen.github.io/cropperjs/) plugins together.
In Bluimp you can get enough code (there is a codeigniter class in their site) to handle file upload in codeigniter.
Please try with cropper js. i have used this and it is very easy and it will full fill your requirement
https://github.com/fengyuanchen/cropper
Create A Image model and paste the code
<?php
class Image_model extends CI_Model {
public function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->library('upload');
$this->load->library('image_lib');
}
public function do_resize($filename)
{
$source_path = 'uploads/' . $filename;
$target_path = 'uploads/thumb/thumb_'.$filename;
$config_manip = array(
'image_library' => 'gd2',
'source_image' => $source_path,
'new_image' => $target_path,
'maintain_ratio' => TRUE,
'width' => 150,
'height' => 150
);
$this->image_lib->initialize($config_manip);
$this->load->library('image_lib', $config_manip);
if (!$this->image_lib->resize()) {
echo $this->image_lib->display_errors();
die();
}
}
public function img_upload()
{
$config = array(
'upload_path' => "uploads",
'allowed_types' => "*",
'overwrite' => TRUE,
'max_size' => "5048000", // Can be set to particular file size , here it is 2 MB(2048 Kb)
'max_height' => "3000",
'max_width' => "3000"
);
$this->upload->initialize($config);
$this->load->library('upload', $config);
if($this->upload->do_upload()) {
$response = array('upload_data' => $this->upload->data());
$this->do_resize($response['upload_data']['file_name']);
}
/*else{
$error = array('error'=>$this->upload->display_errors());
//print_r($error);die();
}*/
}
}
Call this function like this in your controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Post extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('image_model');
}
public function add() {
if(isset($_FILES)){
$config = $this->image_model->img_upload();
$file_data = $this->upload->data();
$data['feature_image'] = $file_data['file_name'];
}
$lat_id = $this->your_model->save($data);
}

Upload file and save its path in database using codeingiter

I wish to upload a file to folder and then save its path in database, but i got stuck in first step only
whenever i am trying to upload a file i am getting a message
You did not select a file to upload
the code that i used is
view
<?php
echo form_open_multipart('recruiter/adddata);
$data = array(
'type'=>'file',
'name'=>'userfile',
'class'=>'fileinput btn-info',
'id'=>'filename3',
'data-filename-placement'=>'inside',
'title'=>'Resume'
);
echo form_upload($data);
$data = array(
'type'=>'submit',
'class'=>'btn btn-danger',
'name'=>'submit',
'content'=>'Submit'
);
echo form_button($data);
echo form_close();
?>
Controller
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'doc|docx|pdf';
$config['max_size'] = 10000;
$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());
print_r($error); //only for checking purposes
}
else
{
$data = array('upload_data' => $this->upload->data());
print_r($data); //only for checking purposes
}
Can anyone please tell how can i upload the file and save its path in database
Make some changes like:
echo form_upload($data);
to
<?php echo form_open_multipart();?>
Controller function part:
//start of file upload code
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
$this->upload->do_upload();
$data = $this->upload->data();
//end of file upload code

Upload image using codeigniter controller

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

Categories