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
Related
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"));
}
Am a new user to CodeIgniter, have looked at other posts and the answers given sadly don't solve this issue.
Am using a form to create records (also uploads image file and creates link to image as field in db) This all works. I am now trying to edit a particular record. I have a view with the form and this works and is pre-filled from the db using $id = $this->uri->segment(3) to grab the correct record - this all works.
Where it fails is then in updating the record.
My controller...
function edit_stock_vehicle_record()
{
$this->load->library('form_validation');
// field name, error message, validation rules
$this->form_validation->set_rules('title', 'Title', 'trim|required');
$this->form_validation->set_rules('make', 'Make', 'trim|required');
$this->form_validation->set_rules('model', 'Model', 'trim|required');
$this->form_validation->set_rules('fuel', 'Fuel Type', 'trim|required');
$this->form_validation->set_rules('enginesize', 'Engine Size', 'trim|required');
$this->form_validation->set_rules('trans', 'Transmission', 'trim|required');
$this->form_validation->set_rules('reg_no', 'Registration Number', 'trim|required');
$this->form_validation->set_rules('year', 'Year', 'trim|required');
$this->form_validation->set_rules('colour', 'Colour', 'trim|required');
$this->form_validation->set_rules('mileage', 'Mileage', 'trim|required');
$this->form_validation->set_rules('long_desc', 'Description', 'trim|required');
$this->form_validation->set_rules('purchase_price', 'Purchase Price', 'trim|required');
$this->form_validation->set_rules('sale_price', 'Sale Price', 'trim|required');
if($this->form_validation->run() == FALSE)
{
$data['main_content'] = 'vehicle_display2';
$this->load->view('includes/template', $data);
}
else
{
$this->load->model('manage_model');
if($query = $this->manage_model->edit_stock_vehicle_record())
{
$data['main_content'] = 'vehicle_added';
$this->load->view('includes/template', $data);
}
else
{
$data['main_content'] = 'add_vehicle4';
$this->load->view('includes/template', $data);
}
}
}
My model....
function edit_stock_vehicle_record()
{
$this->load->helper('array');
$this->load->helper('html');
$id = $this->uri->segment(3);
$config['upload_path'] = 'c:/wamp/www/honest/images';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '5000';
$config['overwrite'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$data['main_content'] = 'imageupload';
$this->load->view('includes/template', $data);
echo "FAILED";
}
else
{
$image_data = $this->upload->data();
$vehicle_update_data = array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->load->helper('url');
$id = $this->uri->segment(3);
$update = $this->db->update('stock_vehicles', $vehicle_update_data, array('id' => $id));
return $update;
}
}
I have also tried versions using....
$this->db->where('id', $id);
$this->db->update('stock_vehicles', $vehicle_update_data);
But this also fails, it seems as if the $id is not being recognized correctly.
If I remove the above and just use $this->db->update('stock_vehicles', $vehicle_update_data); it does indeed update every record in the db (doh!) Fortunately there was no 'real' data in there when I discovered this!
Not sure why it is not picking up the $id - all input gratefully received.
Cheers,
DP.
I have a view with the form and this works and is pre-filled from the
db using $id = $this->uri->segment(3) to grab the correct record -
this all works.
Do NOT do this for the form update. Just include the id in a hidden form field. Much easier, safer, etc.
echo form_hidden( 'id', $id );
first you must load the url helper in your Controller:
$this->load->helper('url');
then you should try this code:
$id = $this->uri->segment(3);
$vehicle_update_data =array(
'title' => $this->input->post('title'),
'make' => $this->input->post('make'),
'model' => $this->input->post('model'),
'fuel' => $this->input->post('fuel'),
'enginesize' => $this->input->post('enginesize'),
'trans' => $this->input->post('trans'),
'reg_no' => $this->input->post('reg_no'),
'year' => $this->input->post('year'),
'colour' => $this->input->post('colour'),
'mileage' => $this->input->post('mileage'),
'long_desc' => $this->input->post('long_desc'),
'purchase_price' => $this->input->post('purchase_price'),
'sale_price' => $this->input->post('sale_price'),
'image' => $image_data['file_name']
);
$this->db->WHERE('id',$id)->update('your_table',$vehicle_update_data);
return true;
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.
I have a form which accepts some text input fields and a file field (used to upload image).
My problem is like that, if I did not fill one of the required fields and I have selected a valid image file, I will get an error message about the missing field, but the image will be uploaded. The Controller is:
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
// Go to another page
}
}
public function upload_image()
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
}
As I know, if one rule failed, other fields and operations will be canceled and the form will be loaded again, or other operations will be done.
Thank you,,,
you need to upload the image when validation is true only. so remove your public function upload_image() and write the functionalists inside validation true statement as given below.
defined('BASEPATH') OR exit('No direct script access allowed');
class Manage extends MY_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$config = array(
array(
'field' => 'item_name',
'label' => 'Item name',
'rules' => 'required'
),
array(
'field' => 'item_code',
'label' => 'Item code',
'rules' => 'required|is_unique[_items.item_code]'
),
array(
'field' => 'item_description',
'label' => 'Item description',
'rules' => 'required'
),
array(
'field' => 'item_img',
'label' => 'Item image',
'rules' => 'callback_upload_image'
)
);
$this->form_validation->set_rules($config);
$this->form_validation->set_message('is_unique', 'Item code (' . $this->input->post('item_code') . ') already exists.');
if($this->form_validation->run() == FALSE)
{
// Render the entry form again
}
else
{
$config['upload_path'] = './items_images';
$config['max_size'] = 1024 * 10;
$config['allowed_types'] = 'gif|png|jpg|jpeg';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if(isset($_FILES['item_img']) && !empty($_FILES['item_img']['name']))
{
if($this->upload->do_upload('item_img'))
{
$upload_data = $this->upload->data();
$_POST['item_img'] = $upload_data['file_name'];
return TRUE;
}
else
{
$this->form_validation->set_message('upload_image', $this->upload->display_errors());
return FALSE;
}
}
else
{
$_POST['item_img'] = NULL;
return FALSE;
}
}
// Go to another page
}
}
I found this very helpful post here. The author wrote his own rules to validate the file chosen by user to upload. Code sample:
$this->form_validation->set_rules('file', '', 'callback_file_check');
public function file_check($str){
$allowed_mime_type_arr = array('application/pdf','image/gif','image/jpeg','image/pjpeg','image/png','image/x-png');
$mime = get_mime_by_extension($_FILES['file']['name']);
if(isset($_FILES['file']['name']) && $_FILES['file']['name']!=""){
if(in_array($mime, $allowed_mime_type_arr)){
return true;
}else{
$this->form_validation->set_message('file_check', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('file_check', 'Please choose a file to upload.');
return false;
}
}
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();
}