Codeigniter form submit with file upload - php

im trying to write a code where i can submit a form enter the contents in a database, at the same time perform a file upload and have it stored in a folder inside my server
the folder location is called uploads which is located at the root of my site
here is my code
controller (site.php)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_controller {
public function __construct()
{
parent::__construct();
// Your own constructor code
$this->load->model("site_model");
$this->load->helper(array('form', 'url'));
}
public function cmain($type,$page)
{
$data = $this->_initialize_data(); //this is just a bunch of variables that im calling in another function
$data['type'] = $type;
$data['page'] = $page;
$this->load->vars($data);
$this->load->view('site/cmain');
}
public function m1()
{
$this->load->library('upload', $config);
if(isset($_POST['m1']))
{
$suffix = $this->input->post("suffix");
$fn = $this->input->post("fn");
$mn = $this->input->post("mn");
$ln = $this->input->post("ln");
$newdata = array('suffix'=>$suffix,
'fn'=>$fn,
'mn'=>$mn,
'ln'=>$ln,
);
//this code is for the file upload
$config['upload_path'] = 'uploads';
$config['allowed_types'] = '*';
$this->load->library('upload', $config);
$data = array('upload_data' => $this->upload->data());
//end of file upload codes
$this->db->insert('myself', $newdata);
redirect(base_url() . "site/complaint");
}
}
view (cmain.php)
<form action="<?php echo base_url();?>site/m1" name="details" id="details" method="post" enctype="multipart/form-data">
<table class='table' width="100%">
<tr>
<td colspan='2'>
<b><font color="#3B608C">Personal Information</font></b>
</td>
</tr>
<tr>
<td>
Suffix (e.g. Jr., III)
</td>
<td>
<input type="text" name="suffix" id="suffix" value="">
</td>
</tr>
<tr>
<td>
First Name*
</td>
<td>
<input type="text" name="fn" id="fn" value="">
</td>
</tr>
<tr>
<td>
Middle Name*
</td>
<td>
<input type="text" name="mn" id="mn" value="">
</td>
</tr>
<tr>
<td>
Last Name*
</td>
<td>
<input type="text" name="ln" id="ln" value="">
</td>
</tr>
</table>
<table>
<tr>
<td width="50%">
Please attach documents pertinent to these complaints. <br>
(Attach a zip file if more than one document)<br>
</td>
<td align="center">
<input name = "userfile" type="file" class="input-xlarge" id = "userfile" />
</td></tr>
</table>
<input type="submit" value="Submit Form" class="pull-right" id="submit" name="m1"/>
</form>
the form posts properly in the database like the suffix,fn,ln and mn
however the file upload isnt working
i tried my best to follow what the codeigniter docs samples and only got the lines i think i needed
am i doing something wrong?
thanks

finally got it working
i used this for the file upload 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
and changed the
<form action="<?php echo base_url();?>site/m1" name="details" id="details" method="post" enctype="multipart/form-data">
into
<?php echo form_open_multipart('site/c_upload');?>

I think you must have to set file upload preference
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
Form Helper
$this->load->helper(array('form', 'url'));
For further detail have a look at my blog post

Did you set writing permissions for 'uploads' folder? (example: php.net/manual/en/function.chmod.php)
Always do test driven development. I got below code block from this url
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}

Related

Uploaded file not saving in folder

I have tried everything but still i cant figure out why the uploaded file is not saving anywhere.....
My HTML CODE:
<form enctype='multipart/form-data' action='generate_xml.php' method='POST'>
<table>
<tr>
<td>Enter Remote ID :</td> <td> <input type='text' name='remote' required /></td><br /> </tr><tr>
<td>Enter Alter_id : </td><td> <input type='text' name='alter' required/></td> <br /> </tr><tr>
<td>Enter Master ID : </td><td><input type='text' name='master' required/> </td><br /></tr><tr>
<td>Enter Vch ID : </td><td> <input type='text' name='vch' required/> </td><br /></tr><tr>
<td>Enter Date Account : </td><td><input type='text' name='date' required/> </td><br /></tr><tr>
<td>Choose a file to upload: <input name='uploadedfile' type='file' /></td><br /></tr>
<tr><td>
<input type='submit' value='submit' /></td>
</tr>
</table>
</form>
Here's my Code
if(! empty($_FILES['uploadedfile']['name']))
{
$this->config->load('je_settings',TRUE);
$tally_folder_path = $this->config->item('tally_folder_path');
$template_file_path = FCPATH;
$tally_folder_path="/home/torrez/Public/";
$file_type = $_FILES['uploadedfile']['type'];
$allowed = array('text/csv','text/comma-separated-values');
if( ! empty($_FILES['uploadedfile']['name']) && in_array($file_type, $allowed))
{
$tally_src_file = $tally_folder_path . basename( $_FILES['uploadedfile'] ['name']);
$name = basename( $_FILES['file']['name']);
move_uploaded_file($name, $tally_folder_path);
}
else
{
die("No file specified or Format not supported");
}
Please help!!!
Include src file path instead of file file path....
$tally_src_file = $tally_folder_path . basename( $_FILES['uploadedfile']['name']);
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $tally_src_file);
Change name to tmp_name and $_FILES['uploadedfile']
$name = $_FILES['uploadedfile']['tmp_name'];
you can try this this might help you
your code is:
$file_type = $_FILES['uploadedfile']['type'];
$allowed = array('text/csv','text/comma-separated-values');
there will be problem with allowed type array
you define it like
$allowed = array('csv','txt','jpg');
Remember to give 777 permission to the folder to which you uploading files.
I think then it will work.
as Its recommended to not use $_FILES['file']['type']
in place of that you can use
$ext = filetype ( string $filename );
it return extension of file.
can refer: http://php.net/manual/en/function.filetype.php
I hope it will help you!
I would recommend you to used the codeigniter uploading library.
https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
-> Make sure that the path you are uploading is real and writable
-> Dump your $_FILES and see if it displays the right value and array index
Here is my sample code when uploading:
if (isset($_FILES['userfile']) && is_uploaded_file($_FILES['userfile']['tmp_name'])) {
$config['upload_path'] = $path = 'Your Path'; //MAKES SURE THIS PATH IS WRITABLE AND A REAL PATH
$config['allowed_types'] = 'csv';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['remove_spaces'] = true;
$config['overwrite'] = true;
$config['encrypt_name'] = true;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//error in upload
var_dump($this->upload->display_errors());
}
else
{
//success upload
var_dump($this->upload->data());
}
}

Uploading multiples files in CodeIgniter using plain PHP

I am new to CodeIgniter. I've tried uploading my files using as follows:
(createAlbum.php)
<form method="post" action="createAlbum_db.php" enctype="multipart/form-data">
<table>
<tr>
<td>Album Name: </td><td><input type="text" name="album_name"></td>
</tr>
<tr>
<td>Photos for album: </td><td><input type = "file" name="photos[]" multiple="true"></td>
</tr>
<tr>
<td><input type="submit" value="Create Album"></td>
</tr>
</table>
</form>
(createAlbum_db.php)
for ($i=0; $i < count($_FILES['photos']['name']);$i++) {
if (move_uploaded_file(base_url().'assets/images/'.$_FILES['photos']['name'][$i],$_FILES['photos']['tmp_name'][$i])) {
echo '<br>success';
} else {
echo '<br>Failure';
echo $_FILES['photos']['error'][$i];
}
}
My assets directory lies in the same directory where application and system files reside.
What I am not being able to figure out is what should I keep in
move_uploaded_file(**DESTINATION????**,$_FILE['photos']['tmp_name']);
I have gone through most of the post and I found CodeIgniter's native uploader class difficult to use.
Codi. provides upload function for that
<?php
$config['upload_path'] = // Here Goes Path;
$config['allowed_types'] = // Here Goes allowed file types;
$config['max_size'] = // you can validate max. size;
$config['max_width'] = '';
$config['max_height'] = '';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload())
{
echo $this->upload->display_errors();
}
else
{
$img = $this->upload->data();
$img_name = $img['file_name'];
}
?>
Just Like this, you can upload single file....
Since you need path on server use realpath('assets/images/') instead of base_url().

How to save image in folder using CodeIgniter?

I am new to CodeIgniter. I want to know how to save an image in a folder. But I wrote the code like image name was stored in a table. But I want to store the image in a folder and retrieve image from the folder. Here I am using the code to store image name in table:
In Controller:
public function product()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('productname','Product Code','trim|required');
$this->form_validation->set_rules('productcode','Product Code','trim|required');
$this->form_validation->set_rules('productprice','Product Price','trim|required');
$this->form_validation->set_rules('quantity','Quantity','trim|required');
$this->form_validation->set_rules('uploadimage','Upload Image','trim_rquired');
if($this->form_validation->run()==FALSE)
{
$this->index();
}else
{
$data['query']=$this->main_model->product_db();
$this->load->view('query_view',$data);
}
}
In Model:
public function product_db()
{
$data=array(
'productname'=>$this->input->post('productname'),
'productcode'=>$this->input->post('productcode'),
'productprice'=>$this->input->post('productprice'),
'quantity'=>$this->input->post('quantity'),
'image'=>$this->input->post('uploadimage')
);
$query=$this->db->get("product");
if($query->num_rows())
{
$this->db->insert('product',$data);
$query=$this->db->get("product");
$this->session->set_userdata($data);
return $query->result();
}
return false;
}
In View:(form page)
<?php echo validation_errors('<p class="error">'); ?>
<?php echo form_open("main/product"); ?>
<p>
<label for="product_name">Product Name:</label>
<input type="text" id="productname" name="productname" value="<?php echo set_value('product_name'); ?>" />
</p>
<p>
<label for="ProductCode">Product Code</label>
<input type="text" id="productcode" name="productcode" value="<?php echo set_value('productcode'); ?>" />
</p>
<p>
<label for="productprice">Product Price:</label>
<input type="text" id="productprice" name="productprice" value="<?php echo set_value('productprice'); ?>" />
</p>
<p>
<label for="Quantity">Quantity:</label>
<select name="quantity" id="quantity" value="<?php echo set_value('quantity'); ?>" /><option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
</p>
<p>
<label for="Uploadimage">Upload Image:</label>
<input type="file" name="uploadimage" id="uploadimage" value="<?php echo set_value('quantity'); ?>" />
</p>
<p>
<input type="submit" class="greenButton" value="submit" />
</p>
<?php echo form_close();
?>
In View(query_view Page):
<?php
echo "<table border='2'>
<tr>
<th>productid</th><th>productname</th><th>productcode</th><th>productprice</th>
<th>quantity</th><th>image</th>
</tr>";
foreach($query as $r)
{
echo "<tr>";
echo "<td>".$r->productid."</td>"."<td>".$r->productname."</td>".
<td>".$r>productcode."</td>"."<td>".$r->productprice."</td>"."<td>"
.$r->quantity."</td>"." <td>".$r->image."</td>";
echo "</tr>";
}
echo "</table>";
echo "<br>";
?>
This is just a sample code of uploading an image:
<?php
$configUpload['upload_path'] = './uploads/'; #the folder placed in the root of project
$configUpload['allowed_types'] = 'gif|jpg|png|bmp|jpeg'; #allowed types description
$configUpload['max_size'] = '0'; #max size
$configUpload['max_width'] = '0'; #max width
$configUpload['max_height'] = '0'; #max height
$configUpload['encrypt_name'] = true; #encrypt name of the uploaded file
$this->load->library('upload', $configUpload); #init the upload class
if(!$this->upload->do_upload('uploadimage')){
$uploadedDetails = $this->upload->display_errors();
}else{
$uploadedDetails = $this->upload->data();
}
print_r($uploadedDetails);die;
?>
you are seeking this kind of code
$config['upload_path'] = './files'; //core folder (if you like upload to application folder use APPPATH)
$config['allowed_types'] = 'gif|jpg|png'; //allowed MIME types
$config['encrypt_name'] = TRUE; //creates uniuque filename this is mainly for security reason
$this->load->library('upload', $config);
if (!$this->upload->do_upload('picture_upload')) { //picture_upload is upload field name set in HTML eg. name="upload_field"
$error = array('error' => $this->upload->display_errors());
}else{
//print_r($this->upload->data()); // this is array of uploaded file consist of filename, filepath etc. print it out
$this->upload->data()['file_name']; // this is how you get for example "file name" of file
}
Please follow this guide http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html it has everything in it. If you need help with logic its pretty simple
form -> upload field -> button -> form sent -> check rules if file is OK -> upload file -> save data (filename, filepath...) in table.

Codeigniter upload working offline but not online

Hi I wanted to upload a 100 x 100 pixel image as a logo on my website for each user. It works on my localhost but doesn't work online (image is not uploaded). Well the concept is simple I just upload it and rename the image base on their ID's then display it on their page for them to view it. Another thing, the localhost version changes the image on the specified path but doesn't display it after upload somethimes but sometimes it works just fine. Well that not a big case here I just think that it might be a clue for solving this problem. Here's my code so far:
this is declared on top:
$data['base'] = $this->config->base_url();
$data['check_error'] = false;
$data['error_message'] = array();
$data['id'] = $this->session->userdata('id');
This is the code:
if (isset($_FILES['userfile']) && is_uploaded_file($_FILES['userfile']['tmp_name'])){
$new_name = $data['id'];
$config['upload_path'] = './Logos/';
$config['allowed_types'] = 'jpg|png|gif';
$config['encrypt_name'] = true;
$config['max_size'] = '100';
$config['max_width'] = '100';
$config['max_height'] = '100';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
array_push($data['error_message'], "You have the following errors in your entry:\n");
array_push($data['error_message'], "- Logo must be 100x100 pixels in size not exceeding 100KB with JPG,PNG or GIF format");
array_push($data['error_message'], "\nLogo upload failed.");
$data['check_error'] = true;
}
else
{
$data = array('upload_data' => $this->upload->data());
//DO UPDATE PART HERE
$file = $data['upload_data']['file_name'];
rename($config['upload_path'] . $file, $config['upload_path'] .$new_name.'.jpg');
//GO TO SETTINGS
$this->load->helper('url');
redirect($data['base'].'settings');
}
}
HTML:
<tr>
<td><p class="titles">Logo</p></td>
<td>
<div>
<input type="text" id="fileName" class="file_input_textbox" readonly="readonly">
<div class="file_input_div">
<input type="button" value="Browse" class="file_input_button" />
<input type="file" class="file_input_hidden" onchange="javascript: document.getElementById('fileName').value = this.value" id="upload" name="userfile" />
</div>
</div>
</td>
</tr>
<tr>
<td>
</td>
<td>
<p class="titles">100px x 100px jpg, png or gif only.</p>
</td>
</tr>
<tr>
<td><p class="titles">Current Logo</p></td>
<td>
<img src="<?php if(is_array(#getimagesize($base."Logos/".$id.".jpg"))){echo $base."Logos/".$id.".jpg";}else{echo $base."Logos/default.jpg";} ?>" style="margin:0px 0px 0px 90px;"/>
</td>
</tr>
I also use CodeIgniter_2.1.3 and 5.4.3 in PHP locally and 5.2.17 online. Going nuts haha!
You should look into the file name part. Firstly you have set the condition encrypt_name to true. While you anyway rename your file to the id this is not neccesary.
You set the new filename to be equal to
$data['id'].".jpg"
this will never work if uploaded file is a GIF or PNG image...

Codeigniter - How to add Images to my CRUD methods?

I am working on my second CI application. I have created some simple CRUD methods in my controller. My client has requested that each record includes an image. I have searched the forums and other resources for help but haven’t had much luck.
I have managed to upload files into a directory using the File Uploading Class, my problem though is how to associate the uploaded file/s with the relevant record.
Here are the relevant parts of my MVC.., any help/point in the right direction would be appreciated.
View - admin/locationEdit.php
<form method="post" action="<?php echo $action; ?>">
<div class="data">
<table>
<tr>
<td width="30%">ID</td>
<td><input type="text" name="id" disabled="disable" class="text" value="<?php echo $this->validation->id; ?>"/></td>
<input type="hidden" name="id" value="<?php echo $this->validation->id; ?>"/>
</tr>
<tr>
<td valign="top">Name<span style="color:red;">*</span></td>
<td><input type="text" name="name" class="text" value="<?php echo $this->validation->name; ?>"/>
<?php echo $this->validation->name_error; ?></td>
</tr>
<tr>
<td valign="top">Address<span style="color:red;">*</span></td>
<td><input type="text" name="address" class="text" value="<?php echo $this->validation->address; ?>"/>
<?php echo $this->validation->address_error; ?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="Save"/></td>
</tr>
</table>
</div>
</form>
Controller - location.php
function add(){
// set validation properties
$this->_set_fields();
// set common properties
$data['title'] = 'Add new location';
$data['message'] = '';
$data['action'] = site_url('admin/location/addLocation');
$data['link_back'] = anchor('admin/location/index/','Back to list of locations',array('class'=>'back'));
// Write to $title
$this->template->write('title', 'Admin - Add New Location!');
// Write to $sidebar
$this->template->write_view('content', 'admin/locationEdit', $data);
// Render the template
$this->template->render();
}
function addLocation(){
// set common properties
$data['title'] = 'Add new location';
$data['action'] = site_url('admin/location/addLocation');
$data['link_back'] = anchor('admin/location/index/','Back to list of locations',array('class'=>'back'));
// set validation properties
$this->_set_fields();
$this->_set_rules();
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$path_to_uploads='./uploads';
$config['upload_path'] = $path_to_uploads;
$this->load->library('upload', $config);
$upload_data=$this->upload->data();
$file_name=$upload_data['file_name'];
$full_file_path = $path_to_uploads.'/'.$file_name;
// run validation
if ($this->validation->run() == FALSE){
$data['message'] = '';
}else{
// save data
$location = array('name' => $this->input->post('name'),
'address' => $this->input->post('address'),
'image_url' => $full_file_path);
$id = $this->locationModel->save($location);
// set form input name="id"
$this->validation->id = $id;
// set user message
$data['message'] = '<div class="success">add new location success</div>';
}
// Write to $title
$this->template->write('title', 'Admin - Add New Location!');
// Write to $sidebar
$this->template->write_view('content', 'admin/locationEdit', $data);
// Render the template
$this->template->render();
}
Within your upload function, get the path of the uploaded file:
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$path_to_uploads='./uploads';
$config['upload_path'] = $path_to_uploads;
$this->load->library('upload', $config);
//add this
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$error = $this->upload->display_errors();
echo "<script>alert($error);</script>";
}else{
$upload_data=$this->upload->data();
$file_name=$upload_data['file_name'];
$full_file_path = $path_to_uploads.'/'.$file_name;
}
then you can return $full_file_path back to the method that called it and insert it into the db, or just insert directly.

Categories