Codeigniter Upload function does not work - php

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

Related

Codeigniter renaming image file is not working

I am using codeigniter and I'm trying to upload image files.
Everything is working fine, but I am unable to change the uploaded file name to a custom name.
I've tried everything for the past 5 hours, nothing is working.
If anyone can help, it would be great.
I just need to rename the uploaded file to custom_name.jpg
Controller file
public function uploadimage() {
$config['overwrite'] = TRUE;
$config['file_name'] = 'custom_name.jpg';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config['upload_path'] = './uploads/';
$config["max_size"] = 1024;
$config["max_width"] = 400;
$config["max_height"] = 400;
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
$this->data['error'] = $this->upload->display_errors();
} else {
echo "success";
}
}
VIEW file
<?php echo form_open_multipart('admin/uploadimage'); ?>
<?php echo form_upload('userfile'); ?><br />
<?php echo form_submit('upload', 'Upload');?>
<?php echo form_close(); ?>
just remove custom extension from file_name and append extension of file uploaded.
public function uploadimage() {
$config['overwrite'] = TRUE;
$config['file_name'] = 'custom_name';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config['upload_path'] = './uploads/';
$config["max_size"] = 1024;
$config["max_width"] = 400;
$config["max_height"] = 400;
$this->load->library('upload', $config);
if(!$this->upload->do_upload()) {
$this->data['error'] = $this->upload->display_errors();
} else {
echo "success";
}
}
You can also use rename function to rename file after successful upload.
Also check these.
Upload directory is writable and the path can be absolute or relative.
Set preferences by calling the initialize() method, if you auto-load the class $this->upload->initialize($config)
You have some restriction on file size, also check your image size.

Posting a file to CodeIgniter backend

I'm trying to post a file to my CodeIgniter backend in the simplest way possible.
I want to fire an API call from Postman like this:
And my PHP function is looking like this right now:
public function runk_image_put()
{
$image = $this->upload->data();
$id = $this->get('id');
$this->response($image, REST_Controller::HTTP_OK);
}
I'm pretty sure that:
$image = $this->upload->data();
Is not the correct way of grabbing the posted file. What is the correct way?
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['overwrite'] = TRUE;
$config['encrypt_name'] = FALSE;
$config['remove_spaces'] = TRUE;
if ( ! is_dir($config['upload_path']) ) die("THE UPLOAD DIRECTORY DOES NOT EXIST");
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('data')) {
echo 'error';
} else {
return array('upload_data' => $this->upload->data());
}
}
and in your controller use this:
$this->data['data'] = $this->do_upload();
and make the form as form-data or if you use binary send a header of what the file is like jpeg or what and then echo the file

CodeIgniter Image Upload Function

How do I upload an image when I'm trying to save other data along with it? When the form submits, it hits the save function:
function save() {
$this->save_data($_POST, $_FILES);
}
function save_data($post_data, $file_data) {
// if theres an image
if(!empty($file_data['image']['size'])) {
$path = '/images';
$this->upload_image($path);
}
}
function upload_image($path) {
// CI is looking for $_FILES super global but I want to pass that data in
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$this->upload->data('image');
$this->upload->do_upload('image');
}
I can't figure out how to actually pass the file data to another function. All the examples I've seen shows the form submitting to a function that uploads the function right from it. I want to do the uploading from another function though.
if you are trying to check if file is actually beeing uploaded do following
//this is optional
if (empty($_FILES['userfile']['name'])) {
$this->form_validation->set_rules('userfile', 'picture', 'required');
}
if ($this->form_validation->run()) { //if using validation
//validated
if (!empty($_FILES['userfile']['name'])) {
//picture is beeing uploaded
$config['upload_path'] = './files/pcitures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
//$error = array('error' => $this->upload->display_errors());
} else {
//no error, insert/update in DB
$tmp = $this->upload->data();
echo "<pre>";
var_dump($tmp);
echo "</pre>";
}
} else { ... }
}
My mistake was related to folder permissions.
For those of you that are looking to split the upload functionality into multiple functions:
Controller:
$save_data = $this->save_model->save_data($_POST, $_FILES);
Model:
function save_data($data, $file) {
// check if theres an image
if (!empty($file['image']['size'])) {
// where are you storing it
$path = './images';
// what are you naming it
$new_name = 'name_' . random_string('alnum', 16);
// start upload
$result = $this->upload_image($path, $new_name);
}
}
function upload_image($path, $new_name) {
// define parameters
$config['upload_path'] = $path;
$config['allowed_types'] = 'jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $new_name;
$this->load->library('upload', $config);
// upload the image
if ($this->upload->do_upload('image')) {
// success
// pass back $this->upload->data() for info
} else {
// failed
// pass back $this->upload->display_errors() for info
}
}

Codeigniter Rename file on upload

I'm trying to add time as the prefix of the image name along with the original name when uploading, But I couldn't figure it out. Please help me with the following code to add a prefix to my original file name when uploading.
<?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'] = 'Public/uploads/';
$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 = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?>
You can encrypt file name with use of CI native option:
$config['encrypt_name'] = TRUE;
OR
You can do it with your own code:
$new_name = time().$_FILES["userfiles"]['name'];
$config['file_name'] = $new_name;
For some reasons, consecutive calls to the do_upload function doesn't work. It sticks to the first filename set by the first function call
$small_photo_url = $this->upload_photo('picture_small', $this->next_id.'_small ');
$medium_photo_url = $this->upload_photo('picture_medium', $this->next_id.'_medium');
$large_photo_url = $this->upload_photo('picture_large', $this->next_id.'_large ');
The filenames will all be "00001_small", "00001_small1", "00001_small2"
given the following configurations
function upload_photo($field_name, $filename)
{
$config['upload_path'] = 'Public/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $filename;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())...
I think it's because this line doesn't work the second time you call it. It does not set the configurations again
$this->load->library('upload', $config);
==========================================================================
Solution to the problem faced during consecutive do_upload function calls:
// re-initialize upload library
$this->upload->initialize($config);
/* Conf */
$new_name = time().$_FILES["userfiles"]['name'];
$config['file_name'] = $new_name;
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$config['file_ext_tolower'] = TRUE;
/* Load the upload library */
$this->load->library('upload', $config);
For what you are exactly looking for, this worked for me:
$path = $_FILES['image']['name'];
$newName = "<Whatever name>".".".pathinfo($path, PATHINFO_EXTENSION);
when you use do_upload() function its rename file name if already exists and upload file
System->libraries->Upload.php
default function of do_upload() return true or false
replace
return $this->upload_path.$this->file_name;
and in another file
<input type='file' name='userfile'/>
<?php
$upload_file_name = $this->upload->do_upload('userfile');
$finalname;
if (!$upload_file_name) {
$finalname = 'default.png';
} else {
$split_data_upload_file_name = explode("/", $upload_file_name);
foreach ($split_data_upload_file_name as $i => $value) {
$finalname = $value;
}
}
?>
$config['file_name'] = $new_name;
Just add it align with the config codes.
This should be after the upload.
Process the filename you want here:
$a=$this->upload->data();
rename($a['full_path'],$a['file_path'].'file_name_you_want');
Try This:
$config['file_name'] = "yourCustomFileName";
If your $config is with this code: $config['encrypt_name'] = TRUE;
the name of your file will be forced to rename with a encrypt name, just remove the code.
Solution 1: Upload file with new customized and specific name (Note: this answer is applicable when you are submitting a unique name of a record, for example student name is a unique value in a record then you will use $_POST['student_name'])
$config['file_name'] = str_replace(' ', '_', $_POST['anyUniqueValue']);
//any Other unique value that you are using to submit with this file
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;
Solution 2: Upload file with new unique name
$config['file_name'] = time();
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;
Solution 3: Upload file with new unique name using codeigniter's default option
$config['encrypt_name'] = TRUE;
if you do multiple file upload, maybe you can try update library Upload.php
on system/libraries/Upload.php. On function do_upload()
$this->file_name = $this->_prep_filename($_file['name']);
to
$this->file_name = time().'_'.$this->_prep_filename($_file['name']);

Upload path on Codeigniter returns "the upload path doesn't seem to be valid"

Now i've tried most of the fixes that i've read, most of them mention about APPPATH, base_url(), real path and etc. but i really don't know why all of them didn't work, what worked for me is that i've used the actual path, not a url but the one with the C:\xampp\htdocs.. blah blah blah.. now i've read one thread that url and directory aren't the same thing.. and the upload_path accepts only directory path and i mean the actual location of the uploads folder on the server not the URL.. now my question is how come APPPATH don't work. as what i know it the actual directory path. but when i tried to display is it return only "../applicaiton/" what really is the best path to be used on the $config['upload_path'] on the upload.php specially when deploying it to an actual server it is really a nuisance finding the directory path of your upload folder, NOTE im not using the initialize() method i'm putting my configs on config/upload.php
EDITS:
i have this on a separate file... upload.php
<?php
$config['upload_path'] ='./uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['max_width'] = '1600';
$config['max_height'] = '1200';
and this is my controller
if($this->upload->do_upload('image'))
{
//Did something here
}
else
{
//Did something for errors like display_errors()
}
and end result is it displays "the upload path doesn't seem to be valid"
and i've tried these line of code also
Trial 1:
$config['upload_path'] ='./uploads/';
Trial 2:
$config['upload_path'] ='uploads/';
Trial 3:
$config['upload_path'] ='/admin/assets/uploads/';
Trial 4:
$config['upload_path'] ='./admin/assets/uploads/';
Trial 5:
$config['upload_path'] ='admin/assets/uploads/';
the only thing that works is this
$config['upload_path'] ='C:\xampp\htdocs\practice\admin.abcgencon\admin\assets\uploads'';
and using the last part as a path is kinda messy so i've tried also APPPATHbut it doesn't work also it also display "../application"..
as #cryptic said i've posted this code snippet.
Question, you tried realpath and APPPATH seperately?
In Codeigniter APPPATH points to the application folder.
Example: (place your folder outside the application folder, just saying if you did not do that way) let's say the folder where we want to place the files called images.
So what you need to do is to combine realpath() and APPPATH
$image_path = realpath(APPPATH . '../images');
and pass it to your config
$config['upload_path'] = $image_path;
Create your file upload directory say uploads outside of application directory or at the root directory of CI, and set the upload path as follows:-
$config['upload_path'] = realpath(FCPATH.'uploads');
FCPATH: Path to the front controller where index.php exists (root of CI)
The above code runs on both server and local.
This is how file uploading is done in CI
$cat_image_name = $_FILES["cat_image"]["name"] ;
//file uploading params
$config['upload_path'] = './uploaded_files/categories';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $image_id."_ipad";
$config['remove_spaces'] = TRUE;
//Loading Library - File Uploading
$this->load->library('upload', $config);
//Upload the image(Ipad)
if (!empty($cat_image_name))
{
$this->upload->do_upload('cat_image');
$data = array('upload_data' => $this->upload->data());
$category_image_ipad = $data['upload_data']['file_name'];
$img_extension = $data['upload_data']['file_ext'];
}
try this
$config['upload_path'] = '../uploads/;
It's working very well for me
use it:
$config['upload_path'] = $_SERVER['DOCUMENT_ROOT']."/uploads/";
//$this->config->item('upload_path');
file upload requires a multipart form. For this, you must have included a form helper.
goto config folder, click autoload and find the $autoload['helper'] = array(); and put 'form' :
$autoload['helper'] = array('form');
for controller:
$config = array(
'upload_path' => "./assets/",
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $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->user_model->create_photo($post_image);
redirect('');
}
for model:
public function create_photo($post_image){
$data = array(
'pri' => $this->input->post('price'),
'descrip' => $this->input->post('title'),
'post_image' => $post_image
);
return $this->db->insert('table_name', $data);
}
Tested on Windows & Linux:
$path = realpath(".");
$path .= "/uploads/profile_images";
Here uploads is the uploads directory on root.
FCPATH: front controller path where index.php exists or root folder
APPPATH: application folder
Create a uploads folder under root folder:
$config['upload_path'] = realpath(FCPATH.'uploads');
Create a uploads folder under application folder:
$config['upload_path'] = realpath(APPPATH.'uploads');
In case: If you have created the uploads folder outside of root folder:
$config['upload_path'] = realpath($_SERVER['DOCUMENT_ROOT'].'/uploads');
It is very simple:
Just copy your all $config in new php file called upload.php and put it in cofig folder.
You path will work ok.
Here is upload.php file contents:
<?php
$config['upload_path'] = site_url().'uploads';
$config['allowed_types'] = 'gif|jpg|png|jpeg|html|pdf';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['file_ext_tolower'] = TRUE;
$config['overwrite'] = FALSE;
$config['max_filename'] = 0;
$config['encrypt_name'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['detect_mime'] = TRUE;
$config['mod_mime_fix'] = TRUE;
?>
But please keep $config data in upload_file controller as well.For example:
public function do_upload(){
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'gif|jpg|png|jpeg|html|pdf';
$config['max_size'] = 0;
$config['max_width'] = 0;
$config['max_height'] = 0;
$config['file_ext_tolower'] = TRUE;
$config['overwrite'] = FALSE;
$config['max_filename'] = 0;
$config['encrypt_name'] = TRUE;
$config['remove_spaces'] = TRUE;
$config['detect_mime'] = TRUE;
$config['mod_mime_fix'] = TRUE;
//Alternately you can set preferences by calling the initialize function. Useful if you auto-load the class:
$this->upload->initialize($config);
if (!$this->upload->do_upload('userfile'))
{
$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);
}
}
It is simple...

Categories