i'am not able to do upload image with lines of code in function add()
just provide me with some solution for uploading image
public function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('image', 'image', 'required');
$this->form_validation->set_rules('text', 'text', 'required');
$this->form_validation->set_error_delimiters('<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>', '</strong></div>');
if ($this->form_validation->run())
{
**$data_to_insert = array(
'image' => $this->input->post('image'),
'text' => $this->input->post('text'),**
);
if($this->home_banner_model->insert_home_banner($data_to_insert)){
$data['flash_message'] = TRUE;
}else{
$data['flash_message'] = FALSE;
}
}
}
$data['main_content'] = 'admin/home_banner/add';
$this->load->view('includes_admin/template', $data);
}
$config = array(
'upload_path' => 'uploadPath',
'allowed_types' => 'jpg,jpeg',
'max_size' => 1500
);
$this->load->library('upload', $config);
if(isset($_FILES['field_name']) && $_FILES[field_name]['name'] != NULL)
if($this->upload->do_upload('field_name'))
{
$upload_data = $this->upload->data();
$data_to_insert = array(
'attachment_link' => 'uploadPath/'.$upload_data['file_name'],
'attachment_size' => $upload_data['file_size']
// u can add parameters as for ur table to save
);
$this->home_banner_model->insert_home_banner($data);
}
else
{
echo $this->upload->display_errors();
}
Related
I am having a problem with inserting file_path to database and file upload in folder using Codeigniter, I have a form field where user can upload any jpg|png|gif file. But how will I get the file_path of that particular file uploaded and insert it into database and file are stored in floder.
my controller code
public function enqry(){
$data = array();
$postData = array();
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 10240;
$this->load->library('upload', $config);
//if add request is submitted
if ( ! $this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}else {
print_r('Image Uploaded Successfully.');
}
if($this->input->post('postSubmit')){
//form field validation rules
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
//prepare post data
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s")
/*'passport_details'=>$this->input->post('passport_details')*/
);
//validate submitted form data
if($this->form_validation->run() == true){
//insert post data
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
//load the add page view
public function log_enq(){
$this->load->view('templates/header');
$this->load->view('enquiry_reg');
$this->load->view('templates/footer');
}
My view code
<div class="form-group">
<label for="title">File Upload</label>
<input type="file" name="upload" placeholder="upload">
</div>
My model code
public function insert_enq($data = array()) {
$insert2 = $this->db->insert('tbl_enquiry', $data);
if($insert2){
return $this->db->insert_id();
}else{
return false;
}
}
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('imageUploadForm', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
and add $image variable to your your query like
$arrayName = array(
'imapge' => $image,
'more_column' => $more_column_values);
public function enqry(){
$data = array();
$postData = array();
$postData['upload_path'] = './uploads/';
$postData['allowed_types'] = 'gif|jpg|png';
$postData['max_size'] = 10240;
$this->load->library('upload', $postData);
if (!$this->upload->do_upload('upload')) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('user_con/error', $error);
}
else {
$data = $this->upload->data('file_name');
$image = 'your_path'.$data;
}
if($this->input->post('postSubmit')){
$this->form_validation->set_rules('name', 'post name', 'required');
$this->form_validation->set_rules('email', 'post email', 'required');
$this->form_validation->set_rules('mobile', 'post number', 'required');
$this->form_validation->set_rules('nationality', 'post nationality', 'required');
$this->form_validation->set_rules('location','post location','required');
$postData = array(
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'mobile' => $this->input->post('mobile'),
'nationality' => $this->input->post('nationality'),
'location'=>$this->input->post('location'),
'statuse' => '0',
'created_at' => date("Y-m-d H:i:s"),
'upload' => $image
);
if($this->form_validation->run() == true){
$insert2 = $this->user_mod->insert_enq($postData);
if($insert2){
$this->session->set_userdata('success_msg', 'Post has been added successfully.');
redirect('/User_con/log/');
}else{
$data['error_msg'] = 'Some problems occurred, please try again.';
}
}
}
$data['post'] = $postData;
$data['title'] = 'Create Post';
}
$config = array(
'upload_path' =>'./uploads/',
'allowed_types' =>'jpg|jpeg|png|gif',
'max_size' => '5000KB');
$this->load->library('upload',$config);
$this->upload->initialize($config);
Replace this code your code....and cheack......
Please help! I was using codeigniter 3 mvc and my code worked just fine. Then I moved to hmvc and my uploads no longer function. Below is my code:
class Home extends MY_Controller
{
function __construct()
{
parent::__construct();
$this->load->model('User_m', 'user');
$this->load->library('upload');
}
public function register()
{
$data['services'] = $this->user->get_service_list();
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
public function apply()
{
$directoryname = $this->input->post('company').'/documents';
if (!is_dir('customer_documents/'.$directoryname))
{
mkdir('./customer_documents/' . $this->input->post('name_of_org').'/documents', 0777, TRUE);
}
//Field Rules
$this->form_validation->set_rules('company', 'Company/', 'trim|required|min_length[6]');
$this->form_validation->set_rules('address', 'Physical Address', 'trim|required');
$this->form_validation->set_rules('tel', 'Tel', 'trim|required');
$this->form_validation->set_rules('postal_address', 'Postal Address', 'trim|required');
$this->form_validation->set_rules('contact_name', 'Contact Name', 'trim|required|min_length[6]');
$this->form_validation->set_rules('contact_number', 'Contact Number', 'trim|required|min_length[6]');
$this->form_validation->set_rules('position', 'Position', 'trim|required|min_length[6]');
$this->form_validation->set_rules( 'email', 'Email', 'trim|required|valid_email|min_length[7]');
$name_array = array();
$count = count($_FILES['userfile']['size']);
foreach($_FILES as $key=>$value)
for($s=0; $s<=$count-1; $s++)
{
$_FILES['userfile']['name']=$value['name'][$s];
$_FILES['userfile']['type'] = $value['type'][$s];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'][$s];
$_FILES['userfile']['error'] = $value['error'][$s];
$_FILES['userfile']['size'] = $value['size'][$s];
$config = [
'upload_path' => './customer_documents/'.$directoryname,
'allowed_types' => 'gif|jpg|png|pdf',
'max_size' => '1000000',
'overwrite' => FALSE,
'remove_spaces' => TRUE,
'encrypt_name' => FALSE
];
$this->upload->initialize($config);
$this->upload->do_upload();
$file_data = $this->upload->data();
$name_array[] = $file_data['file_name'];
}
if($this->form_validation->run() == FALSE && !$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$data['services'] = $this->customer->get_service_list();
//Load Template
$data['page_class'] = 'register-page';
$data['title'] = 'Registration';
$data['content_view'] = 'Home/register_v';
$this->template->login_template($data);
}
else
{
$names= implode(',', $name_array);
$data = array(
'name_of_org' => $this->input->post('name_of_org'),
'address' => $this->input->post('address'),
'tel' => $this->input->post('tel'),
'postal_address' => $this->input->post('postal_address'),
'contact_name' => $this->input->post('contact_name'),
'contact_number' => $this->input->post('contact_number'),
'role' => 'admin',
'position' => $this->input->post('position'),
'email' => $this->input->post('email'),
'userfile' => $names,
'service' => $this->input->post('service_id'),
);
//Insert User
$this->user->register($data);
//isset Message
$this->session->set_flashdata('success', 'You have successfully submitted your registration.');
//Redirect
redirect('Home/register');
}
}
Model:
class User_m extends CI_MODEL{
function __construct()
{
parent::__construct();
$this->table = 'users';
}
function register($data)
{
$this->db->insert($this->table, $data);
}
}
When I use the above code to upload files using mvc it works perfectly well but when I transfered it to hmvc it just post other form fields to the database without files yet also creating directory without uploading any files. What might be the problem? Anyone with a solution for this I am stuck. Please help!
Try with absolute path
(!is_dir(FCPATH.'customer_documents/'.$directoryname))
and fix that in all places accordingly.
Also CI_MODEL should be CI_Model
Today My teacher in my college give me a task about CodeIgniter, he gives me this Controller
public function __construct()
{
parent::__construct();
$this->load->model('Gallery_model');
$this->load->helper(['url','html','form']);
$this->load->database();
$this->load->library(['form_validation','session','image_lib']);
}
public function index()
{
$data = ['images' => $this->Gallery_model->all()];
$this->load->view($this->layoutgaleri, $data);
}
public function add(){
$rules = [
[
'field' => 'caption',
'label' => 'Caption',
'rules' => 'required'
],
[
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/layoutgaleriadd');
}
else
{
/* Start Uploading File */
$config = [
'upload_path' => './asset/images/',
'allowed_types' => 'gif|jpg|png',
'max_size' => 2000,
'max_width' => 640,
'max_height' => 480
];
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/layoutgaleriadd', $error);
}
else
{
$file = $this->upload->data();
//print_r($file);
$data = [
'file' => 'asset/images/' . $file['file_name'],
'caption' => set_value('caption'),
'description' => set_value('description')
];
$this->Gallery_model->create($data);
$this->session->set_flashdata('message','Gambar sudah ditambahkan..');
redirect('admin/Galeri');
}
}
}
public function edit($id){
$rules = [
[
'field' => 'caption',
'label' => 'Caption',
'rules' => 'required'
],
[
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
]
];
$this->form_validation->set_rules($rules);
$image = $this->Gallery_model->find($id)->row();
if ($this->form_validation->run() == FALSE)
{
$this->load->view('admin/layoutgaleriedit',['image'=>$image]);
}
else
{
if(isset($_FILES["userfile"]["name"]))
{
/* Start Uploading File */
$config = [
'upload_path' => './asset/images/',
'allowed_types' => 'gif|jpg|png',
'max_size' => 2000,
'max_width' => 640,
'max_height' => 480
];
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('admin/layoutgaleriedit',['image'=>$image,'error'=>$error]);
}
else
{
$file = $this->upload->data();
$data['file'] = 'asset/images/' . $file['file_name'];
unlink($image->file);
}
}
$data['caption'] = set_value('caption');
$data['description'] = set_value('description');
$this->Gallery_model->update($id, $data);
$this->session->set_flashdata('message','Gambar sudah diperbarui..');
redirect('admin/galeri');
}
}
public function delete($id)
{
$this->Gallery_model->delete($id);
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
The problem is we had to create a model that handle function delete, so it can delete a photo from the folder too, here it's the model
public function delete($id)
{
try {
$this->db->where('id',$id)->delete('tb_gambar');
return true;
}
//catch exception
catch(Exception $e) {
echo $e->getMessage();
}
}
He gives us a hint to use unlink, but I don't have any idea how to use it, so I try to ask you all for the answer. I hope you all can show me the right answer for my school task
You can delete image from DB and folder in the one function:
public function delete($id)
{
$image = $this->Gallery_model->find($id)->row();
// delete image
if (is_file('image_path/'.$image->file)) {
unlink('image_path/'.$image->file);
}
$this->Gallery_model->delete($id);
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
in controller :
public function delete($id)
{
$image = $this->Gallery_model->find($id)->row();
$this->Gallery_model->delete($id);
// use
delete_files(FCPATH.$image->file); // codeigniter method to delete file
// or use php method
// unlink(FCPATH.$image->file); // php unlink method
$this->session->set_flashdata('message','Gambar sudah dihapus..');
redirect('admin/galeri');
}
if(file_exists(FCPATH.$image->file))
{
unlink(FCPATH.$image->file);
}
here is my delete function and it works
public function delete($id){
$image = $this->M_sizechart->find($id)->row();
$this->M_sizechart->delete($id);
if(file_exists(FCPATH.$image->file)) {
unlink(FCPATH.$image->file);
}
$this->session->set_flashdata('message','Image has been deleted..');
redirect(base_url("sizechart"));
}
My controller is but how I insert a default image name in database if user not upload any image when he/she input his details in form.
<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
class Student extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('student_model');
$this->load->model('hostelinfo_model');
$this->load->model('options_model');
$this->load->model('upload_model');
$this->load->library('form_validation');
$this->load->library('upload');
}
public function index() {
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('student_id', 'Student ID', 'required|trim|xss_clean|callback_student_id_check');
$this->form_validation->set_rules('student_name', 'Student Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('father_name', 'Father Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('program_name', 'Progrem Name', 'required|trim|xss_clean');
$this->form_validation->set_rules('mobile', 'Mobile No', 'required|trim|xss_clean|is_unique[student.mobile]|max_length[11]|min_length[11]');
$this->form_validation->set_rules('email', 'Email ID', 'trim|xss_clean|is_unique[student.email]|valid_email');
$this->form_validation->set_rules('hostel_name', 'Hostel Name', 'required|trim|xss_clean');
if ($this->form_validation->run() == FALSE) {
$this->load->view('header1');
$this->load->view('book_hostel');
$this->load->view('footer');
} else {
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'jpeg|jpg|png';
$config['max_size'] = '2048';
$config['encrypt_name'] = true;
$this->upload->initialize($config);
if (!$this->upload->do_upload('image_name')) {
$image_data = "noimage.png";
$data['error'] = $this->upload->display_errors();
$this->load->view('header');
$this->load->view('book_hostel', $data);
$this->load->view('footer');
}else{
$this->form_validation->set_rules('image_name', 'Upload Image', 'trim|xss_clean');
if ($this->form_validation->run($this) == FALSE) {
$data['error'] = '';
$this->load->view('header1');
$this->load->view('book_hostel', $data);
$this->load->view('footer');
}
}
$image_data = $this->upload->data();
$data = array(
'image_name' => $image_data['file_name'],
'student_id' => $this->input->post('student_id'),
'student_name' => $this->input->post('student_name'),
'father_name' => $this->input->post('father_name'),
'program_name' => $this->input->post('program_name'),
'mobile' => $this->input->post('mobile'),
'email' => $this->input->post('email'),
'hostel_name' => $this->input->post('hostel_name')
);
$this->student_model->form_insert($data);
//$this->sendEmail();
$data['message'] = 'Data Inserted Successfully';
redirect('hostel');
}
}
}
first check if user not upload any image
$default_image=0;
if($_FILES['image_name']['tmp_name'] != '') {
if (!$this->upload->do_upload('image_name')) {
$default_image =1;
}else{
$this->form_validation->set_rules('image_name', 'Upload Image', 'trim|xss_clean');
if ($this->form_validation->run($this) == FALSE) {
$data['error'] = '';
$this->load->view('header1');
$this->load->view('book_hostel', $data);
$this->load->view('footer');
}
}
}else {
$default_image=1;
}
if($default_image) {
$image_data = "noimage.png";
$data['error'] = $this->upload->display_errors();
$this->load->view('header');
$this->load->view('book_hostel', $data);
$this->load->view('footer');
}
check to see if the file was uploaded.
if (!empty($_FILES['image']['name']))
{
if (!$this->upload->do_upload('image'))
{
// Name isn't empty so a file must have been selected
$data['error'] = $this->upload->display_errors();
$this->load->view('header');
$this->load->view('book_hostel', $data);
$this->load->view('footer');
}
else
{
$image_data = $this->upload->data();
}
}else
{
// No file selected - set default image
$image_data['file_name'] = "noimage.png"
}
$data = array(
'image_name' => $image_data['file_name'],
'student_id' => $this->input->post('student_id'),
'student_name' => $this->input->post('student_name'),
'father_name' => $this->input->post('father_name'),
'program_name' => $this->input->post('program_name'),
'mobile' => $this->input->post('mobile'),
'email' => $this->input->post('email'),
'hostel_name' => $this->input->post('hostel_name')
);
$this->student_model->form_insert($data);
//$this->sendEmail();
$data['message'] = 'Data Inserted Successfully';
redirect('hostel');
This could be refactored further but the point is that you can check $_FILES['field_name']['name'] to see if a file was selected.
In php when I am updating user info into database with profile image then updation is working but when I'm not selecting image then the update is not working.
Here is my controller:
public function editvendor($id = '') {
$this->authAdLogin();
if ($id == '') {
redirect(admin_url() . 'vendorlisting');
} else if ($this->db->where('id', $id)->get('tbl_vendor')->num_rows() == 0) {
redirect(admin_url() . 'vendorlisting');
} else {
$data['vendor_data'] = $this->db->where('id', $id)->get('tbl_vendor')->result_array();
$vendor_data = $data['vendor_data'];
$this->form_validation->set_rules('contact_name', 'Name', 'trim|xss_clean|required');
$this->form_validation->set_rules('contact_mobile', 'Mobile Number', 'trim|xss_clean|required|numericmin_length[10]|max_length[10]');
$this->form_validation->set_rules('contact_land', 'Landline Number', 'trim|xss_clean|numeric');
$this->form_validation->set_rules('contact_email', 'Email', 'trim|xss_clean|required|valid_email');
$this->form_validation->set_rules('incorporation_date', 'Incorporation Date', 'trim|xss_clean|required');
$this->form_validation->set_rules('pancard_no', 'Pan Card', 'trim|xss_clean|required');
$this->form_validation->set_rules('tan_no', 'Tan Number', 'trim|xss_clean|required');
$this->form_validation->set_rules('tin_no', 'Tin Number', 'trim|xss_clean|required');
$this->form_validation->set_rules('service_no', 'Service Number', 'trim|xss_clean|required');
if ($this->form_validation->run() == false) {
$this->load->view('admin/header');
$this->load->view('admin/sidemenu');
$this->load->view('admin/editvendor', $data);
} else {
$id = $vendor_data[0]['id'];
$upload_dir = './uploads/' . $vendor_data[0]['vendor_id'];
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
if (isset($_FILES['profile_pic']['name'])) {
$config['upload_path'] = './uploads/' . $vendor_data[0]['vendor_id'];
$config['allowed_types'] = 'gif|jpg|png';
/* $config['max_size'] = '1000000';
$config['max_width'] = '10240000';
$config['max_height'] = '7680000'; */
$config['file_name'] = "prof_" . rand(1, 5000);
$this->load->library('upload');
$this->upload->initialize($config);
if (!$this->upload->do_upload('profile_pic')) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('ppic_error', $error);
redirect(admin_url() . 'editvendor');
} else {
$data = $this->upload->data();
$prof_pic = $data['file_name'];
}
} else {
$prof_pic = $vendor_data[0]['profile_pic'];
}
$update_data = array(
'contact_name' => $this->input->post('contact_name'),
'contact_mobile' => $this->input->post('contact_mobile'),
'contact_land' => $this->input->post('contact_land'),
'contact_email' => $this->input->post('contact_email'),
'mailing_address' => $this->input->post('mailing_address'),
'incorporation_date' => $this->input->post('incorporation_date'),
'pancard_no' => $this->input->post('pancard_no'),
'tan_no' => $this->input->post('mailing_address'),
'mailing_address' => $this->input->post('tan_no'),
'tin_no' => $this->input->post('tin_no'),
'service_no' => $this->input->post('service_no'),
'web_url' => $this->input->post('web_url'),
'business_address' => $this->input->post('business_address'),
'other_certificates' => $this->input->post('other_certificates'),
'facebook_link' => $this->input->post('facebook_link'),
'twitter_link' => $this->input->post('twitter_link'),
'linkedin_link' => $this->input->post('linkedin_link'),
'googleplus_link' => $this->input->post('googleplus_link'),
'about_company' => $this->input->post('about_company'),
'industry_segment' => $this->input->post('industry_segment'),
'ayurveda' => $this->input->post('ayurveda'),
'homeopathy' => $this->input->post('homeopathy'),
'unani' => $this->input->post('unani'),
'profile_pic' => $prof_pic,
);
$this->db->where('id', $id);
$this->db->update('tbl_vendor', $update_data);
$this->session->set_flashdata('vendor_edit', 'Successfully updated.');
redirect(admin_url() . 'editvendor/' . $id);
}
}
}
Please
provide any solution.