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.
Related
I have spent days trying to make this work based on the examples in the documentation but I am missing something
I have a simple image upload form on my local server where users can upload image and it need to store in local folder but It not work . I am also take a permission to my folder is 777 but still its taking problem what I can do that. My Image is not upload to the specific directory in codeigniter in my Local wamp server its display directory is not correct error.
MY Controller Code is given below
public function do_upload()
{
$upPath= './uploads/';
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config = array(
'upload_path' => $upPath,
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
);
$this->load->library('upload', $config);
if(!$this->upload->do_upload('userfile'))
{
$data['imageError'] = $this->upload->display_errors();
print_r($data['imageError']);
}
else
{
$imageDetailArray = $this->upload->data();
return $imageDetailArray['file_name'];
}
}
public function add_article(){
if($this->session->userdata('writer_logged_in')){
if ($this->form_validation->run() === FALSE)
{
$data['main_content']="writer/profile";
$this->load->view('include/template',$data);
}
else
{
$image = $this->do_upload();
echo $image;
die();
$result=$this->writer_model->new_article();
if($result==1){
$this->session->set_flashdata('article_insertion',"Article has been successfully added.");
redirect('writer/profile');
}
}
}
else{
redirect('site');
}
}
My View Code is given below
<form method="post" action="<?php echo base_url(); ?>writer/add_article" enctype="multipart/form-data">
<?php echo validation_errors(); ?>
<div class="form-group">
<label for="title">Title</label>
<input type="text" name="title" id="title" placeholder="Article title" value="<?php echo set_value('title'); ?>" class="form-control" />
</div>
<div class="form-group">
<label>Image</label>
<input type="file" id="image" name="userfile" class="form-control" value="<?php echo set_value('userfile'); ?>"/>
</div>
<div class="form-group">
<label for="body">Article detail</label>
<textarea name="body" id="body" class="form-control" rows="10" cols="40" placeholder="Provide Articles content. Basic HTML is allowed."><?php echo set_value('body'); ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
Now My Error is Resolved I have just clear my temp caches and now my image is upload to the specific folder . Thanks For you cooperation and Answers. Now I am Continued my work.......!
I recommend this code:
$upPath = './uploads/';
if(!file_exists($upPath))
{
mkdir($upPath, 0777, true);
}
$config['upload_path'] = $upPath;
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('userFile')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
for more details please read the CodeIgniter manual
Hi friends in my code image upload in my folder but it's not saved in database am not knowledge about CI so help me for this
view code for upload image,
<form role="form" method="post" enctype="multipart/form-data">
<fieldset class="form-group">
<input type="hidden" name="txt_hidden" value="" class="form-control">
</fieldset>
<fieldset class="form-group">
<label class="control-label" for="formGroupExampleInput">Add Main Caregory</label>
<input type="text" value="<?php echo set_value('p_name'); ?>" placeholder="Main Category" name="p_name" class="form-control">
</fieldset>
<fieldset class="form-group">
<label class="control-label" for="formGroupExampleInput2">Order</label>
<input type="text" name="order_id" placeholder="Order Id" value="<?php echo set_value('order_id'); ?>" class="form-control" id="formGroupExampleInput2">
</fieldset>
<fieldset class="form-group">
<label class="control-label" for="formGroupExampleInput2">Status ( 0 active , 1 inactive)</label>
<input type="text" name="status" placeholder="Status" value="<?php echo set_value('status'); ?>" class="form-control" id="formGroupExampleInput2">
</fieldset>
<fieldset class="form-group">
<label class="control-label" for="formGroupExampleInput2">Image</label>
<input type="file" name="image" placeholder="Category Image" value="<?php echo set_value('image'); ?>" class="form-control" id="formGroupExampleInput2">
</fieldset>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add Category</button>
</div>
</form>
in My controller
use this for add category with an image
function add_main_category()
{
$this->form_validation->set_rules('p_name', 'Main Category', 'required|is_unique[main_category.p_name]');
$this->form_validation->set_rules('order_id', 'Order Id');
$this->form_validation->set_rules('status', 'Status');
$this->form_validation->set_rules('image', 'Category Image', 'callback_cat_image_upload');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('master/add_main_category');
}
else
{
$p_name = strtolower($this->input->post('p_name'));
$order_id = strtolower($this->input->post('order_id'));
$status = strtolower($this->input->post('status'));
$image = strtolower($this->input->post('image'));
$data = array(
'p_name' => $p_name,
'order_id' => $order_id,
'status' => $status,
'image' => $image
);
$insert = $this->m->CategoryAdd($data);
if($insert){
$this->session->set_flashdata('success_msg','Category Created Successfully!!');
}
else{
$this->session->set_flashdata('error_msg', 'Failed to delete Category');
}
redirect('admin/main_cat');
}
}
and for image upload use this in controller
function cat_image_upload(){
if($_FILES['image']['size'] != 0){
$upload_dir = './uploads/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'userimage_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('image')){
$this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('cat_image_upload', "No file selected");
return false;
}
}
table main_category in column image
everything is working only no image name save in database!
help me with this.
Thanks in advance!
You can't store the image in the way you used as:
$image = strtolower($this->input->post('image'));
Get the image file name once it is uploaded. Here is your modified code:
if (!$this->upload->do_upload('image')){
$this->form_validation->set_message('cat_image_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
$data = array('upload_data' => $this->upload->data());
$doc_file_name = $data['upload_data']['file_name']; // Use this file name to store in database
return true;
}
Now i am trying to upload pdf files by the form in php but when i upload it, it doesn't work because function is_uploaded_file($_FILES['file']['tmp_name']) return false
How can i solve it please ??
I am using localhost and I verify php.ini
; Whether to allow HTTP file uploads.
; http://php.net/file-uploads
file_uploads = On
; Temporary directory for HTTP uploaded files (will use system default if not
; specified).
; http://php.net/upload-tmp-dir
upload_tmp_dir = "E:/wamp/tmp"
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 50M
This is my code :
Class
<?php
require '../includes/master.inc.php';
// Kick-out users who aren't logged in as an admin
$auth->requireAdmin('../login_admin_cp.php');
if (isset($_POST['btnsubmit'])) {
$error->blank($_POST['field_name'], "field_name");
if ($error->ok()) {
$field_name = $_POST['field_name'];
if (is_uploaded_file($_FILES['file']['tmp_name'])) {
// exit;
$mypath = "upload/";
$file_name = $_FILES['file']['name'];
$tmp = $_FILES['file']['tmp_name'];
$n = $mypath . $file_name;
$t = $_FILES['file']['size'];
$filesize = round($t / 1024) . " KB";
$extintion = strchr($n, ".");
$extintion = strtolower($extintion);
$file_extintion_allow = array(".pdf");
if ($n == "") {
echo "Error in upload";
} elseif (!in_array($extintion, $file_extintion_allow)) {
echo "من فضلك ادخل المادة بطريقة صحيحة";
exit;
} else {
//rename the file when upload by query name
$quaryname = rand(11111, 99999);
$rename = "../" . $mypath . $quaryname . $extintion;
$URL = substr($rename, 10, strlen($rename));
move_uploaded_file($tmp, $rename);
if (!empty($_POST['hide'])) {
$hide = $_POST['hide'];
$db->query("insert into field (field_name,url,hide)values('$field_name','$URL','$hide')");
$sess->set_flashdata('success_msg', 'تم حفظ المادة بنجاح');
redirect("field_new.php");
} else {
$db->query("insert into field (field_name,url,hide)values('$field_name','$URL','0')");
$sess->set_flashdata('success_msg', 'تم حفظ المادة بنجاح');
redirect("field_new.php");
}
}
} else {
exit;
}
} else {
$sess->set_flashdata('error_msg', 'حقل المادة فارغ');
}
}
// View
include('views/header.php');
include('views/field_form_new.php');
include('views/footer.php');
?>
Form
<!-- Form elements -->
<div class="grid_9">
<div class="module">
<h2><span> رفع المادة</span></h2>
<div class="module-body">
<?php echo $error;?>
<form action="field_new.php" method="post" name="myform" enctype="multipart/form-data">
<p>
<label> اسم المادة</label>
<input type="text" class="input-medium" name="field_name" value="" />
</p>
<p style="font-size:14px"> رفع المادة </p>
<p>
<label> الرابط</label>
<input type="text" class="input-medium" name="link" value="<?php $link; ?>" />
</p>
أو<br/> <br/>
<p>
<input type="hidden" class="input-medium" name="MAX_FILE_SIZE" value="1000000">
<label>رفع الملف </label>
<input type="file" class="input-medium" name="file" />
</p>
<p>
<input type="checkbox" name="hide" value="1" />تفعيل المادة
</p>
<fieldset>
<input class="submit-green" type="submit" name="btnsubmit" value="اضافة" />
</fieldset>
</form>
</div> <!-- End .module-body -->
</div> <!-- End .module -->
<div style="clear:both;"></div>
</div> <!-- End .grid_6 -->
Maybe the file is to big or the destination directory is not writeable for php/apache.
Check the folder permission "E:/wamp/tmp" and try to upload a smaller file.
If a smaller file works, check these values in the php.ini file:
post_max_size
max_input_time
memory_limit
I have the following:
<form id="set" method="post" action="<?php echo $base_url; ?>schedule" enctype="multipart/form-data">
<?php
for($i=0;$i<10;$i++) {
?>
<input type="file" name="file[]" class="selective_file">
<input type="checkbox" name="name[]" value="<?php echo $name[$i]; ?>" style="display:none;"/>
<?php
}
?>
<input type="submit" value="Post />
</form>
The client has to submit 10 photos and once they click the button and the form is submitted, the schedule controller gets the files as follows
public function index() {
$files = $this->input->post('files');
$name = $this->input->post('name');
print_r($files);
print_r($name);
}
I know that for uploading files in CI, the following has always worked for me
if(!$this->upload->do_upload('file')) {
$error = array('error' => $this->upload->display_errors());
print_r($error);
} else {
$pic = $this->upload->data();
}
How do I identify the files with CI so that it can be uploaded successfully while looping thru the array of files with the correct corresponding name from the checkbox field?
Kindly have a visit on following link: Demo link for problem
You can view that form is not showing submitted values and not uploading file.
Following is form code :
<form id="frm" name="frm" method="post" enctype="multipart/form-data">
<fieldset class="fieldset2">
<legend class="legend2">Add Bid Type</legend>
<div class="form_fields">
<p>
<label for="subject" class="label2">Bid Type:</label>
<input type="input" id="type" name="type" class="textfield2" />
</p>
<p>
<label for="subject" class="label2">Bid Type Code:</label>
<input type="input" id="code" name="code" class="textfield2" />
</p>
<p>
<label for="description" class="label2">Bid Type Description:</label>
<textarea id="description" name="description" class="textarea2"></textarea>
</p>
<p>
<label for="userfile" class="label2">Icon:</label>
<input type="file" id="userfile" name="userfile" class="input_file" />
</p>
</div>
</fieldset>
<fieldset class="none">
<p>
<input type="submit" id="btnsubmit" name="btnsubmit" class="btn" value="Add" />
<input type="reset" id="btnreset" name="btnreset" class="btn" value="Reset" />
</p>
</fieldset>
</form>`
And following is controller code :
function create() {
$data = '';
echo '<pre>';
echo 'below is Post Fields Data:<br>';
print_r($this->input->post());
echo '<br>Post Fields Data Ends: ';
echo '</pre>';
$this->form_validation->set_rules('type', 'Bid Type', 'trim|required|xss_clean');
$this->form_validation->set_rules('code', 'Bid Type Code', 'trim|xss_clean');
$this->form_validation->set_rules('description', 'Bid Type description', 'trim|xss_clean');
$data['errors'] = array();
if ($this->form_validation->run()) {
$data = array(
'code' => $this->form_validation->set_value('code'),
'type' => $this->form_validation->set_value('type'),
'description' => $this->form_validation->set_value('description'),
);
if (!is_null($this->bid_types->create_bid_type($data))){
$data['errors']['success'] = 'Record Successfully Added!';
} else {
$errors = $this->bid_types->get_error_message();
foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
}
$config['upload_path'] = base_url().'resource/images/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())
{
$data['errors']['upload'] = 'Not Uploaded';
//$data['errors']['upload'] = $this->upload->display_errors();
//$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
}
else
{
$data['errors']['upload'] = 'Yes Uploaded';
//$data['errors']['upload'] = $this->upload->data();
//$data = array('upload_data' => $this->upload->data());
//$this->load->view('upload_success', $data);
}
echo '<pre>';
print_r($this->upload->data());
echo '</pre>';
} /* END OF FORM VALIDATRION RUN */
if(!$this->input->is_ajax_request() && !$this->input->get_post('is_ajax'))
{
$this->load->view('bend/bid_type/create', $data);
}
} /* END OF FUNCTION CREATE */
Can some one guide me what and where Iam doing wrong and how it can be rectrified.
File data appears in $_FILE not in $_POST.
I think this line is your problem:
$config['upload_path'] = base_url().'resource/images/uploads/';
This $config['upload_path'] should point to a file system path, not a URL.
Try something more like:
$config['upload_path'] = realpath(APPPATH . '../resource/images/uploads/');
which will start from your application folder, up one folder then into resource/images/uploads
change it accordingly if its somewhere else.
p.s. Also check your write permissions.
put $this->output->enable_profiler(TRUE) on the first line of create() function, it will show you very usefull information $_POST global to debug your code like
Charles shows that the request from the form submit does contain the post data.
Does anything else happen before the create() function that could wipe the POST data?
I would add an action attribute to the form using echo form_open('/phpdemo/b1/admin/bid_type/create') as described in the user manual.
you can not use
$this->form_validation->set_rules('code', 'Bid Type Code', 'trim|xss_clean');
in multipart , so you must create your own function for validation and use callbacks