Codeigniter can't read file name of uploaded file - php

Trying to read the file name of a file that is uploaded as part of a form. The print_r command that I'm using to test just shows a blank screen. I have read the manual (near the bottom here) pertaining to this and don't understand what I'm doing wrong.
Controller:
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|txt|pdf|xlsx|csv|xls|bmp';
$config['max_size'] = 1000;
$this->load->library('upload', $config);
$file_name = $this->upload->data('file_name');
print_r($file_name);
View:
<?php echo form_open_multipart('Corpmuns/do_upload', array('method' => 'post'));?>
... // some drop-down menus and text fields here
<INPUT TYPE="file" NAME="userfile" id="userfile" >
</form>

You didn't do the upload action so the file was not uploaded yet. That's why you can't get the uploaded file's name. Because it does not exists.
Code $this->upload->do_upload('userfile') and make sure the file is uploaded successfully before you get the filename.

Call do_upload function from upload library.
Update Controller:
public function do_upload() {
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|txt|pdf|xlsx|csv|xls|bmp';
$config['max_size'] = 1000;
$this->load->library('upload', $config);
if ($this->upload->do_upload('userfile')) { //use this function
$data['error'] = false;
$upload_data = $this->upload->data();
$data['data'] = $upload_data;
$data['msg'] = 'Image Successfully Uploaded.';
} else {
$data['msg'] = $this->upload->display_errors('', '<br>');
}
print_r($data)
}

if ( ! $this->upload->do_upload('input_name'))
{
echo $this->upload->display_errors();
}
else
{
$file=$this->upload->data();
echo $image=$file['file_name'];//Set file name to varilable
}
}

<form action="" enctype="multipart/form-data" method="post"
name="uploadfile">
you should add enctype="multipart/form-data"

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.

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 File Upload error: 'You did not select a file to upload'

I am using codeigniter 3, getting error like You did not select a file to upload. in do_upload() function, but normal php function move_uploaded_file() works fine. i referred most of the answers from stackoverflow but i did not get solution.
I think it may be in wamp issue, but i did not get clearly where it is.
if this code works in your machine then it will be issue in my wamp php or Apache settings.
View: (upload.php)
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<?php echo form_open_multipart('welcome/do_upload'); ?>
<input id="sfile" type="file" name="file">
<input type="submit" value="Submit">
<?php echo form_close(); ?>
</body>
</html>
Controller: (welcome.php)
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()) //not working
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
echo $basename = $_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'],$config['upload_path'].$basename);
// move_uploaded_file() works fine
}
AS per CI 3 you need to pass name attribute in your $this->upload->do_upload('').
So you need to pass name attribute in it
$this->upload->do_upload('file');
Check size of file you have uploaded because you set $config['max_size'] = '100';. It means you will not able to upload file size for more then 100 kb
Read File Uploading Class
It could be related to a post loss due to 301-error.
Try replacing
<?php echo form_open_multipart('welcome/do_upload'); ?>
with (work around)
<form action="do_upload" method="post" enctype="multipart/form-data">
If it works, there's some error in routing configs
First load upload library and then after initialize config data.
And pass attribute name of your input file type in $this->upload->do_upload('file').
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); # Load upload library
$this->upload->initialize($config); # Initialize
if ( ! $this->upload->do_upload('file'))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
}
}

Multiple file upload in codeigniter: Fatal error: Cannot redeclare my_escapeshellarg() (previously declared in ...\system\libraries\Upload.php:1038)

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

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

Categories