We are trying to upload some files with Codeigniter, and for some reason this piece of code is not working.
Loading the library in "autoload" works perfectly, still, not the best solution, for the obvious reasons.
Curiously, is working in another website that I have.
<?php
// set options
$config['upload_path'] = FCPATH.$path;
$config['allowed_types'] = 'png|jpeg|jpg|gif';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
$config['overwrite'] = TRUE;
$config['max_width'] = 0;
$config['max_height'] = 0;
// check if folder exists
if( ! is_dir($config['upload_path']))
#mkdir($config['upload_path'], 0755, true);
//load upload library
$this->load->library('upload', $config);
//check success of upload
if( ! $this->upload->do_upload($name))
return $this->upload->display_errors();
else
{
// do upload
}
?>
Here is the error:
A PHP Error was encountered
Severity: Notice
Message: Undefined property: xxx::$upload
Filename: core/xxx.php
Line Number: 424
Fatal error: Call to a member function do_upload() on null
First make sure $path is correct var dump($path) and check receiving it.
Second you did not have any {} in if part of do_upload and around the is directory
public function do_upload() {
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'png|jpeg|jpg';
$config['max_size'] = 2048;
$config['encrypt_name'] = TRUE;
$config['max_size'] = '30000'; // Added Max Size
$config['overwrite'] = TRUE;
$config['max_width'] = 0;
$config['max_height'] = 0;
//load upload library
$this->load->library('upload', $config);
$this->upload->initialize($config);
// check if folder exists
if( ! is_dir($config['upload_path'])) {
#mkdir($config['upload_path'], 0755, true);
}
//check success of upload
$name = "userfile"; // Field name
if( ! $this->upload->do_upload($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);
}
}
Make sure on view use echo form_open_multipart('controller/do_upload')
http://www.codeigniter.com/userguide2/libraries/file_uploading.html
Related
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
I am uploading file in codeigniter using
$this->upload->do_upload('image')
but when file moves to particular path the file extension is changed (it's changed to lower case)
for example if I upload file "profile.JPG" it's changes to "profile.jpg"
please change CI system library
default in CI upload library $file_ext_tolower = FALSE.
.system\libraries\upload.php
public $file_ext_tolower = TRUE;
do_upload does this
$config['allowed_types'] = 'gif|jpg|png'
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);
}
}
If you want to use same name / extension you send to save your file. You can use :
$upload_dir= $this->config->item("upload_dir");
$fileName = $_POST['sku_code'].".".$extension;
$filePath = $upload_dir.$fileName;
move_uploaded_file($_FILES["image-file"]["tmp_name"],$filePath );
Useful link :
https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
I tried to upload 2 types of files, image and pdf in different location. But i am getting the following error.
Fatal error: Cannot redeclare my_escapeshellarg() (previously declared in ...\system\libraries\Upload.php:1038).
Here is my controller:
$config['upload_path'] = './uploads/category_imgs/';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile')){
$imgname ='noimage.png';
$image_thumb ='noimage_thumb.png';
} else {
$data = $this->upload->data();
$imgname = $data['file_name'];
$path_parts = pathinfo($imgname);
//$image_path = $path_parts['filename'].'._.'.date("Y-m-d h:i:s").'.'.$path_parts['extension'];
}
$filepath = '';
$config['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
$config['upload_path'] = './uploads/category_brochure/';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('brochure')) {
$data['uploaderror'] = array('error' => $this->upload->display_errors());
} else {
$arrUploadFileDetails = array('upload_data' => $this->upload->data());
$filepath = $arrUploadFileDetails['upload_data']['file_name'];
$filExtension = $arrUploadFileDetails['upload_data']['file_ext'];
}
Can anyone point out my mistake
You've got the following line in there twice:
$this->load->library('upload', $config);
This is then trying to load the library twice, and causing the issue you are having. If you need to change the config for the uploads, then you should use:
$this->upload->initialize($config);
when you set the config for the second upload.
If you have two
<input type="file" name="userfile" multiple="multiple">
And
<input type="file" name="brochure" multiple="multiple">
On the same view page
You could use this do upload function below I use this code with codeigniter form validation callback for multiple file uploads on one page.
public function do_upload() {
foreach ($_FILES as $field_name => $value) {
if ($value['name'] != '') {
$this->load->library('upload');
$this->upload->initialize($this->do_upload_options());
if (!$this->upload->do_upload($field_name)) {
$this->form_validation->set_message('do_upload', $this->upload->display_errors());
return FALSE;
} else {
return TRUE;
}
}
}
}
public function do_upload_options() {
$config = array();
$config['upload_path'] = FCPATH . 'uploads/';
$config['allowed_types'] = 'gif|png|jpg';
$config['max_size'] = '30000';
$config['overwrite'] = TRUE;
$config['max_width'] = '0';
$config['max_height'] = '0';
return $config;
}
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
}
}
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']);