Upload form validation call back error Codeigniter HMVC - php

i have function where i want to upload data and have its upload errors validated.. but the problem is i got this error Unable to access an error message corresponding to your field name Document.
public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules('DOC_NAME', 'Document Name' ,'trim|required');
$this->form_validation->set_rules('DOC_TYPE', 'Document Type' ,'trim|required');
$this->form_validation->set_rules('DOC_DATE', 'Date' ,'trim|required');
$this->form_validation->set_rules('userfile', 'Document', 'callback_pdf_upload');
if($this->form_validation->run($this) == TRUE){
echo "Account Created Successfully";
}else{
$this->add_view();
}
}
function pdf_upload(){
if($_FILES['userfile']['size'] != 0){
$upload_dir = './uploads/pdf';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'pdf';
//$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('userfile')){
$this->form_validation->set_message('userfile', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['userfile'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('userfile', "No file selected");
return false;
}
}
i am well aware of the callback issues of HMVC on code igniter and already have the MY_Form_validation library. what is the error of this ? i also got the error ERROR - 2016-07-15 15:47:35 --> Could not find the language line "form_validation_pdf_upload" on my error logs.

Change this :
$this->form_validation->set_message('pdf_upload', $this->upload->display_errors());

Related

CodeIgniter make file uploads optional

I have found some examples of making the uploads optional but so far it hasn't work for me. I might have missed something so I'm hoping someone might catch it? This is the link to what I am following
https://blog.smalldo.gs/2013/03/optional-file-upload-field-codeigniter/
So far I am able to edit the product if I don't upload a file but if I upload a file, I get a you did not select a file to upload error. Please help. Thank you.
Controller
public function editProduct(){
$this->form_validation->set_error_delimiters('<p class="error">', '</p>');
$this->form_validation->set_rules('inputproductname', 'Name', 'trim|required');
$this->form_validation->set_rules('inputproductdescription', 'Description', 'trim|required');
$this->form_validation->set_rules('inputproductprice', 'Price', 'trim|required');
$inputproductname = $this->input->post('inputproductname');
$inputproductdescription = $this->input->post('inputproductdescription');
$inputproductprice = $this->input->post('inputproductprice');
$inputdateadded = date('Y-m-d');
$inputcurrentproductid = $this->input->post('inputcurrentproductid');
$inputcurrentproductstatus = $this->input->post('inputcurrentproductstatus');
$config['upload_path'] = $this->getProductImageFolderPath();
$config['allowed_types'] = 'jpg|jpeg|png';
$config['max_size'] = 3000;
$config['remove_spaces'] = TRUE;
$config['overwrite'] = TRUE;
$config['file_name'] = $inputproductname;
$this->load->library('upload', $config);
if($this->form_validation->run()==false){
$data['product'] = $this->ProductsModel->getProduct($inputcurrentproductid);
$data['edit'] = "true";
$data['message']='';
$data['inputcurrentproductid'] = $inputcurrentproductid;
$data['inputcurrentproductstatus'] = $inputcurrentproductstatus;
$this->load->view('control/controlMenu/navigationLink');
$this->load->view('control/controlProducts/productDetail',$data);
$this->load->view('control/controlMenu/navigationJquery');
}else{
if(isset($_FILES['upload'])&&$_FILES['upload']['size']>0){
if(!$this->upload->do_upload()){
$this->session->set_flashdata('Form',$this->upload->display_errors());
redirect('Control/ProductDetail/'.$inputcurrentproductid."/".$inputcurrentproductstatus);
}else{
$extension = $this->upload->data('file_ext');
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice,
'imagePath'=>$config['upload_path'].$config['file_name'].$extension,
'dateAdded'=>$inputdateadded
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}else{
$productdetails = array(
'name'=>$inputproductname,
'description'=>$inputproductdescription,
'price'=>$inputproductprice
);
$this->db->trans_start();
$this->ProductsModel->editProduct($inputcurrentproductid,$productdetails);
$error = $this->db->error();
$this->db->trans_complete();
if($this->db->trans_status()===false){
}else{
$this->session->set_flashdata('Form', $inputproductname . ' has been altered on the database');
redirect('/Control/Products');
}
if($error!=''){
$this->session->set_flashdata('Form',$error["message"]);
redirect('/Control/Products');
}
}
}
You didn't tell the upload library from which field to take the file.
$this->upload->do_upload() // <-- no argument for this method provided
If no field name is provided, by default it tries to get the file from userfile field [docs], but your file input is called upload as seen in the code sample. So you should do
if(!$this->upload->do_upload("upload")){
Also, note that on the client side the form with file field should be declared as
<form method="post" action="some_action" enctype="multipart/form-data" />
otherwise file field will be empty too.

Is there a better way of multipart/form-data validation

I have a multipart/form-data with an image upload and some personal data, so I want to include file upload in form validation, I can successfully do this.
However, I now find that there is an issue, ie even if my other form fields have errors and upload file field with no error, then image uploads to folder, how to prevent this, I mean, in my case, If name, email, file fields validation is ok then only file should upload, if name filed validation fails and file field validation ok then file should not upload
here is the code I use:
In Controller:
<?php
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
'profile_img'=>array('field'=>'profile_img', 'label'=>'Design', 'rules'=>'callback__profile_upload')
);
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
function _profile_upload(){
if($_FILES['profile_img']['size'] != 0 && !empty($_FILES['profile_img']) ){
$upload_dir = './profile_pics/';
if (!is_dir($upload_dir)) {
mkdir($upload_dir);
}
$config['upload_path'] = $upload_dir;
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['file_name'] = 'profile_img_'.substr(md5(rand()),0,7);
$config['overwrite'] = false;
$config['max_size'] = '5120';
$this->upload->initialize($config);
if (!$this->upload->do_upload('profile_img')){
$this->form_validation->set_message('_profile_upload', $this->upload->display_errors());
return false;
}
else{
$this->upload_data['file'] = $this->upload->data();
return true;
}
}
else{
$this->form_validation->set_message('_profile_upload', "No file selected");
return false;
}
}
IN VIEW:
<?php echo form_open_multipart();?>
<?php $name_err = (!empty(form_error('name'))) ? 'err' : ' ';
echo form_input('name',set_value('name'), array('placeholder'=>'Name','class'=>" {$name_err } "));
?>
<?php $email_err = (!empty(form_error('email'))) ? 'err' : ' ';
echo form_input('email',set_value('email'), array('placeholder'=>'EMail','class'=>" {$email_err } "));
?>
<?php
echo form_error('profile_img');
echo form_upload(array('name' =>'profile_img', 'class' => 'inputfile inputfile-4', 'id' => 'profile_img'));
?>
<li><input type="submit" class="special" value="Submit" /></li>
Try once like this.I think for images not need to set rules like other fields.
public $_rules = array(
'name'=>array('field'=>'name', 'label'=>'Name', 'rules'=>'trim|required'),
'email'=>array('field'=>'email', 'label'=>'Email', 'rules'=>'trim|required|valid_email'),
);
And
public function profile()
{
$this->load->library('upload');
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
die('success');
}else {
if ($this->_profile_upload()) { //return true if file uploaded successfully otherwise error
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}
}
yes that is very obvious that your file get uploads even any other fields' validation failed. You have to initiate image uploading only after form validation success.
For that simply validate file specific requirement in that callback, and do actual uploads after successful form validation.
I have got a solution from codexWorld, I have asked same question over there, and they replied with a tutorial, If anybody still looking for a solution here is the link
http://www.codexworld.com/codeigniter-file-upload-validation/
in the validation call back, we just want to do the file type check
public function _profile_upload($str){
$allowed_mime_type_arr = array('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('_profile_upload', 'Please select only pdf/gif/jpg/png file.');
return false;
}
}else{
$this->form_validation->set_message('_profile_upload', 'Please choose a file to upload.');
return false;
}
}
and in the main function we just want to do the same as normal, using do_upload and specifying the upload config items, anyhow there will be a second file type check when the function executes, I think that doesn't matter. The code will look like this::
public function profile()
{
$rules = $this->_rules;
$this->form_validation->set_rules($rules);
if($this->form_validation->run()==TRUE){
$config['upload_path'] = 'uploads/files/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024;
$this->load->library('upload', $config);
//upload file to directory
if($this->upload->do_upload('file')){
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
/*
*insert file information into the database
*.......
*/
}else{
$data['error_msg'] = $this->upload->display_errors();
}
}else {
$this->data['content'] = 'frontend/pages/place_order';
$this->load->view('frontend/_layout_main', $this->data);
}
}

how can i check the value of a variable from a controller in codeigniter

I am doing an upload image file in CodeIgniter. I want to trace out the image in my code and update my database path with it. I want to print the $image_path variable in the code below where it was located in my controller.
How can I print the $image_path variable to display or check its value inside the controller or maybe echo it out ?
Here it is:
<?php
public function upload_file()
{
$status = "";
$msg = "";
$file_element_name = 'userfile';
if ($status != "error") {
$config['upload_path'] = './assets/upimages/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload($file_element_name))
{
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else
{
$data = $this->upload->data();
$image_path = $data['full_path'];
if(file_exists($image_path))
{
$status = "success";
$msg = "File successfully uploaded";
}
else
{
$status = "error";
$msg = "Something went wrong when saving the file, please try again.";
}
}
#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg));
}
?>
If I understand the question your asking then you want to view the contents of the $image_path variable.
If all you want is to check this then you could pass it back to the view with the json array ('image_path' => $image_path).
The other option is to var_dump($image_path) however to view this you would need to inspect the post data response on the browser and it may also stop the json from working while you are using the var_dump().
Blinky
try echo $image_path; or print_r($image_path)

Error message not displaying-image upload

In my web application i have to upload an image.In that check the file is upload or not if this not upload dont show any error message
view
public function shopped()
{
$config['upload_path'] = './application/assets/images/shops';
$config['allowed_types'] = 'jpg';
$this->load->library('upload', $config);
$id=$this->input->post('shop_name');
$type=$this->input->post('type');
$this->form_validation->set_error_delimiters('<div class="error" style="color:red">', '</div>');
$this->form_validation->set_rules('shop_name','Business Type','required');
$this->form_validation->set_rules('type',' shop type','required|alpha');
if ($this->form_validation->run() == FALSE)
{
$this->viewcategories();
}
else if (!$this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->viewcategories($error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->businesstype_model->getshop($id,$type);
$success_message='Successfully Added!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesstype/viewcategories');
}
}
viewcategory function
public function viewcategories()
{
$nam=$this->input->post('name');
$rec=$this->businesstype_model->getdata();
$rec_array=array('rec_name'=>$rec);
$this->load->view('admin/header',$rec_array);
$this->load->view('admin/addshop_view',$rec_array);
$this->load->view('admin/footer',$rec_array);
}
I want to display the error message on addshop_view
the error message in my else if condition is not working..whats the reason for that..
plzz give a suggetion..
Try to put this in addshop_view
// Report all PHP errors
error_reporting(E_ALL);
or this
// Report all PHP errors
error_reporting(-1);

why this error happens with codeigniter fileupload?

this is my upload function
public function do_upload()
{
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('customer_photo'))
{
$responce->success = false;
$responce->data['error'] = $this->upload->display_errors();
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->_do_resize($data);
}
echo json_encode($responce);
}
this is the json what im seeing on firebug console
{"success":false,"data":{"error":"<p>The filetype you are attempting to upload is not allowed.<\/p>"}}</p>
any idea why its contain </p> and these <\/p> ?
Regards
According to the manual, $this->upload->display_errors() wraps the error messages in <p> tags.
You can pass parameters for the delimiters, to wrap the errors in what you want.
$this->upload->display_errors('', '');

Categories