upload library
function upload($upload_path = '', $file_name = ''){
$config = $this->config($upload_path);
$this->CI->load->library('upload' ,$config);
//thuc hien upload
if($this->CI->upload->do_upload($file_name)){
$data = $this->CI->upload->data();
}
else{
//khong upload thanh cong
$data = $this->CI->upload->display_error();
}
return $data;
}
function config($upload_path = ''){
//Khai bao bien cau hinh
$config = array();
//thuc mục chứa file
$config['upload_path'] = $upload_path;
//Định dạng file được phép tải
$config['allowed_types'] = 'jpg|png|gif';
//Dung lượng tối đa
$config['max_size'] = '500';
//Chiều rộng tối đa
$config['max_width'] = '1500';
//Chiều cao tối đa
$config['max_height'] = '1500';
//load thư viện upload
$this->CI->load->library('upload', $config);
return $config;
}
edit action
function edit(){
$id = $this->uri->rsegment('3');
$news = $this->news_model->get_info($id);
if(!$news){
$this->session->set_flashdata('message', 'Không tồn tại bài viết này');
redirect(admin_url('news'));
}
$this->data['news'] = $news;
$this->load->library('form_validation'); //load thư viện
$this->load->helper('form'); //load helper
/*===============================================validate và update data===========================================*/
if( $this->input->post() ){
$this->form_validation->set_rules('title' ,'Tiêu đề bài viết ','required');
$this->form_validation->set_rules('content' ,'Nội dung bài viết','required');
if( $this->form_validation-> run()){
$this->load->library('upload_library');
$upload_path = './upload/news';
$upload_data = $this->upload_library->upload($upload_path, 'image');
$image_link = $this->news_model->get_info($id, 'image_link') ;
if( isset($upload_data['file_name']) ){
$image_link = $upload_data['file_name'];
}
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'image_link' => $image_link,
'meta_desc' => $this->input->post('meta_desc'),
'meta_key' => $this->input->post('meta_key'),
'created' => now()
);
if($this->news_model->update($news->id , $data)){
$this->session->set_flashdata('message', 'Cập nhật dữ liệu thành công');
}
else{
$this->session->set_flashdata('message', 'Không cập nhật dữ liệu thành công');
}
//chuyển tới trang danh sách quản trị viên
redirect(admin_url('news'));
}
}
$this->data['temp'] = 'admin/news/edit';
$this->load->view('admin/main' , $this->data);
}
I edited the data are not required to upload photos
when I clicked update button without upload file error occurred
$data = $this->CI->upload->display_error();
this is wrong method call. It should be like this
$data = $this->CI->upload->display_errors();
Related
I need to insert multiple values in the checkbox in Codeigniter. how I can write this in the controller.
I tried so many but the values not inserting .
View.Php
<div class="custom-file">
<input type="checkbox" name="size[]" value="Medium"> M
<input type="checkbox" name="size[]" value="Large">L
<input type="checkbox" name="size[]" value="XL"> XL
</div>
Model
public function product_insert($data)
{
// grab user input
$this->db->insert('product', $data);
return $this->db->insert_id();
}
Controller
public function newProduct()
{
$data = array();
$this->load->library('form_validation');
$this->load->library('image_lib');
$this->load->helper('file');
$this->load->helper('string');
// Load the model
$this->load->model('admin/product_model');
$this->load->model('admin/category_model');
$data['category'] = $this->category_model->active_category_listing();
// $data['brand'] = $this->product_model->brand_listing();
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
// Validating Field
$this->form_validation->set_rules('product_title', 'Title', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('admin/add_product', $data);
}
//insert size checkboxes into database.
$sizeArray = $this->input->post('size'); // Array
$sizeString = implode(",", $sizeArray); // String
else {
$config['upload_path'] = 'uploads/product_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 10024;
$this->load->library('upload', $config);
// upload file to directory
$uploadedFile ='';
if ($this->upload->do_upload('product_img')) {
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $uploadData['full_path'];
$config['new_image'] = 'uploads/product_images/thumb';
$config['create_thumb'] = false;
$config['maintain_ratio'] = TRUE;
$config['width'] = 311;
$config['height'] = 415;
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data['success_msg'] = 'File has been uploaded successfully.';
} else {
$data['error_msg'] = $this->upload->display_errors();
}
// Setting values for tabel columns
$data = array(
'product_title' => $this->input->post('product_title'),
'product_description' => $this->input->post('product_description'),
'product_price' => $this->input->post('product_price'),
'product_discount' => $this->input->post('product_discount'),
'product_quantity' => $this->input->post('product_quantity'),
'sub_category_id' => $this->input->post('sub_category_id'),
'category_id' => $this->input->post('category_id'),
'product_status' => $this->input->post('product_status'),
'product_img' => $uploadedFile,
'product_key' => random_string('alnum',8),
'product_cuttingprice' => $this->input->post('product_cuttingprice'),
'size'=>$sizeString);
);
// Transfering data to Model
$prdID = $this->product_model->product_insert($data);
$upImg = $this->uploadAddtnlImages($prdID);
$this->session->set_flashdata('msg', 'Product Added Successfully');
redirect('admin/product/listProduct/', 'refresh');
}
}
View:-
You must do all name checkbox as an array like this.
<div class="custom-file">
<input type="checkbox" name="size[]" value="Medium"> M
<input type="checkbox" name="size[]" value="Large">L
<input type="checkbox" name="size[]" value="XL"> XL
</div>
Controller:-
public function newProduct()
{
$data = array();
$this->load->library('form_validation');
$this->load->library('image_lib');
$this->load->helper('file');
$this->load->helper('string');
// Load the model
$this->load->model('admin/product_model');
$this->load->model('admin/category_model');
$data['category'] = $this->category_model->active_category_listing();
// $data['brand'] = $this->product_model->brand_listing();
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">','</div>');
// Validating Field
$this->form_validation->set_rules('product_title', 'Title', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('admin/add_product', $data);
}
else {
$config['upload_path'] = 'uploads/product_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 10024;
$this->load->library('upload', $config);
// upload file to directory
$uploadedFile ='';
if ($this->upload->do_upload('product_img')) {
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $uploadData['full_path'];
$config['new_image'] = 'uploads/product_images/thumb';
$config['create_thumb'] = false;
$config['maintain_ratio'] = TRUE;
$config['width'] = 311;
$config['height'] = 415;
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data['success_msg'] = 'File has been uploaded successfully.';
} else {
$data['error_msg'] = $this->upload->display_errors();
}
//insert size checkboxes into database.
$sizeArray = $this->input->post('size'); // Array
$sizeString = implode(",", $sizeArray); // String
// Setting values for tabel columns
$data = array(
'product_title' => $this->input->post('product_title'),
'product_description' => $this->input->post('product_description'),
'product_price' => $this->input->post('product_price'),
'product_discount' => $this->input->post('product_discount'),
'product_quantity' => $this->input->post('product_quantity'),
'sub_category_id' => $this->input->post('sub_category_id'),
'category_id' => $this->input->post('category_id'),
'product_status' => $this->input->post('product_status'),
'product_img' => $uploadedFile,
'product_key' => random_string('alnum',8),
'product_cuttingprice' => $this->input->post('product_cuttingprice'),
'size'=>$sizeString);
);
// Transfering data to Model
$prdID = $this->product_model->product_insert($data);
$upImg = $this->uploadAddtnlImages($prdID);
$this->session->set_flashdata('msg', 'Product Added Successfully');
redirect('admin/product/listProduct/', 'refresh');
}
}
Model Code:-
public function product_insert($data)
{
// grab user input
$this->db->insert('product', $data);
return $this->db->insert_id();
}
Note:- For More info regarding implode().
The implode() function returns a string from the elements of an array.
https://www.php.net/manual/en/function.implode.php
Codeigniter when i update the form others are updating but image path disappears
Form Submit
user name update
password update
image url delete
Form Submit
user name update
password update
Not -> image url delete
CONTROLLER
public function profil_guncelle($id)
{
if(!empty($_FILES['avatar']['name'])){
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['width'] = 150;
$config['height'] = 50;
$config['file_name'] = $_FILES['avatar']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('avatar')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
$this->form_validation->set_rules('user_pass', 'Parola', 'trim|required');
$this->form_validation->set_rules('user_mail', 'E-Posta', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_userdata('profil_guncelle', validation_errors());
$upload_error = array('error' => $this->upload->display_errors());
redirect(base_url().'admin/users/profil/'.$id);
}else{
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
if ($this->Database_Model->profil_guncelle($data, $id) ==true) {
$this->session->set_flashdata('profil_guncelle', 'Bilgileriniz başarıyla güncellendi.');
redirect(base_url().'admin/users/profil/'.$id);
}
}
}
}
DATABASE MODEL
public function profil_guncelle($data, $id){
$this->db->set($data);
$this->db->where('id', $id);
if ($this->db->update('users') ===true) {
return true;
}else{
return false;
}
}
First you are set $picture become '' if $_FILES['avatar']['name'] is empty.
than when you are trying update data
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
of course $picture will be set to '' if the images files are empty. you change the array become :
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
);
if($picture != ''){
$data['avatar'] = $picture;
}
i'm new to codeigniter. i need help to upload a picture and video and save it to folder and database.
here is my controller
public function upload()
{
$this->m_upload->upload();
$this->upload_gambar();
}
public function upload_gambar()
{
//load the helper
$this->load->helper('form');
$config['upload_path'] = 'assets/gallery/images';
$config['allowed_types'] = 'gif|jpg|png|mp4';
$config['max_size'] = '';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->set_allowed_types('*');
$data['upload_data'] = '';
$this->upload->do_upload('uploadan');
redirect(c_upload);
}
and this is my models
public function upload()
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$picture = $_FILES['uploadan']['name'];
$data = array(
'url' => $picture,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
i've already set upload_max_filesize and post_max_size in the php.ini but it still not working. please help me fix this problem. thankyou
Try this
In Controller
$configVideo['upload_path'] = 'assets/gallery/images'; # check path is correct
$configVideo['max_size'] = '102400';
$configVideo['allowed_types'] = 'mp4'; # add video extenstion on here
$configVideo['overwrite'] = FALSE;
$configVideo['remove_spaces'] = TRUE;
$video_name = random_string('numeric', 5);
$configVideo['file_name'] = $video_name;
$this->load->library('upload', $configVideo);
$this->upload->initialize($configVideo);
if (!$this->upload->do_upload('uploadan')) # form input field attribute
{
# Upload Failed
$this->session->set_flashdata('error', $this->upload->display_errors());
redirect('controllerName/method');
}
else
{
# Upload Successfull
$url = 'assets/gallery/images'.$video_name;
$set1 = $this->Model_name->uploadData($url);
$this->session->set_flashdata('success', 'Video Has been Uploaded');
redirect('controllerName/method');
}
In Model
public function uploadData($url)
{
$title = $this->input->post('title');
$details = $this->input->post('details');
$type = $this->input->post('gallery');
$data = array(
'url' => $url,
'title' => $title,
'details' => $details,
'category' => $type
);
$this->db->insert('gallery', $data);
}
Add mimes code for media file in:
application/config/mimes.php
especially for mp4
In this, I want to upload csv files. Validation is not correct but without validation its working.
This is my controller:
public function uploadstatetype()
{
$config['upload_path'] = APPPATH.'/assets/upload/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5000';
with = ' ';
$replace = '"';
$this->load->library('upload', $config);
$this->load->database();
if ( ! $this->upload->do_upload('file_name'))
{
$error = array('error' => $this->upload->display_errors());
$this->managestate($error);
}
else
{
//Insert file info into database
$data = array('upload_data' => $this->upload->data());
$userfile = $data['upload_data']['file_name'];
$this->load->library('csvreader');
$upload_data = $this->upload->data();
$this->load->library('csvreader');
$file = $upload_data['full_path'];
$file_name = $upload_data['userfile'];
$data = $this->csvreader->parse_file($file);
foreach($data as $row)
{
if(($row['state_id']=='')||($row['state_name']==''))
{
$this->session->set_flashdata('msg_excel','Please check the details in the file, some details are empty.');
redirect(base_url().'admin/businesslocation/managestate');
}
else
{
$results_array = array(
'state_id' => $row['state_id'],
'state_name' => $row['state_name']
);
$this->load->model('admin/businesslocation_model');
$this->businesslocation_model->stateupload($results_array);
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesslocation/managestate');
}
}
}
}
And this is my model:
function stateupload($results_array)
{
$this->db->insert('cr_state', $results_array);
}
For eg state_id=1 and state_name="kerala". Then insert is working,when condition is not checked. But when if condition is given it's not working.
Change your condition like this and try
if(empty($row['state_id'])||(empty($row['state_name']))){
I have a form with four fileds like contactemail,contactname,category,comments as of now now i have to add image and doc input in a form,using form i have inserted data to db,how to upload image and doc in codeignatior on form submit
images need to upload in image folder and doc in docs folder
Here is my controller
public function form() {
$this->load->helper('form');
$data = $this->login_model->form();
//loading views
load-view-header
load view page
load-view-footer
}
here my model function
public function form() {
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments
);
$this->db->insert('contact', $data);
return $data;
}
Here is an example. This was put together quickly and is completely untested...at best there may be errors and at worst memory has failed me and I totally missed something but may be a useful example. Let me know if it helps?
View:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<!-- your other form fields for email, name, category, comments can go here-->
<input type="file" name="image" size="20" />
<input type="file" name="doc" size="20" />
<br /><br />
<input type="submit" value="Submit" />
</form>
Controller:
function form()
{
$this->load->helper(array('form', 'url'));
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$data['error'] = "";
//it would be good to be using the form validation class but here is a quick and dirty check for the submit
if (isset($_POST['submit']))
{
if ( ! $this->upload->do_upload('image'))
{
$data['error'] = $this->upload->display_errors();
}
else
{
$image_upload_data = $this->upload->data();
}
unset($config);
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'doc|docx|txt';
$config['max_size'] = '2048';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('doc'))
{
$data['error'] .= "<br />".$this->upload->display_errors();
}
else
{
$doc_upload_data = $this->upload->data();
}
if(!empty($data['error']))
{
$this->load->view('form', $data);
}
else
{
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$doc_file = $doc_upload_data['full_path'];
$image_file = $image_upload_data['full_path'];
$form_data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments,
'doc_file' => $doc_file
);
$image_data['image_name'] = $image_file;
$this->login_model->form($form_data,$image_data);
$this->load->view('upload_success', $data);
}
}
else
{
$this->load->view('form', $data);
}
}
Model
public function form($form_data,$image_data) {
$this->db->insert('contact', $image_data);
$image_data['d_fk'] = $this->db->insert_id();
$this->db->insert('images', $image_data);
}