why this error happens with codeigniter fileupload? - php

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('', '');

Related

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 to fix unwanted double copy of uploaded file?

My code is running fine and adding the files correctly but it is adding one additional copy of uploaded file. What is wrong?
My controller is like this:
public function add_audio(){
$config['upload_path'] = './musics/';
$config['allowed_types'] = 'mp3';
$config['max_size'] = '999999999999999999999';
$this->load->library('upload',$config);
$this->upload->do_upload();
if ( ! $this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
print_r($data['error']);
//line of codes that displays if there are errors
}
else
{
$data['audio'] = $_FILES['userfile']['name'];
$this->load->model('main');
$query = $this->main->insert('audio',$data);
if($query == TRUE){
$this->load->view('admin/success');
}
}
... but it is adding one additional copy of uploaded file. What is wrong?
That's because you're calling do_upload() twice...
public function add_audio()
{
....
$this->upload->do_upload(); // <- FIRST upload (remove this one)
if ( ! $this->upload->do_upload() ) // <- SECOND upload
{
....
Since you may need the conditional logic that handles upload failures, delete the first instance of do_upload().

Upload form validation call back error Codeigniter HMVC

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());

how to submit file using jquery to codeigniter controller

May I ask for your help guys!
I am trying to upload a file and passing all the data to codeigniter controller using jquery.
my view file:
<div class="form-group">
<label class="col-md-4 control-label">Item Image</label>
<div class="col-md-8">
<input class="form-control" type="file" placeholder="" id="itemImage" name="itemImage" data-parsley-required="true" />
</div>
</div>
<button type="button" onclick="add_item();">Sumit</button>
<script>
function add_item(){
$.post('<?php echo site_url('admin_newitem/add_item'); ?>',
{
itemId : $('#itemId').val(),
itemImage : $('#itemImage').val()
},
function(data){
if(data.result=='SUCCESS'){
$('#itemId').val('');
$('#itemImage').val('');
//show success
}else{
//show error
}
},'json'
);
}
</script>
My controller:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if(!$itemImage){
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}
I was able to get the ItemId, and ItemImage but when I check the folder where the image is suppose to be located, it's not there. I think I fail to capture the real file, so, is there a way for me to get this done?
As you suggest, I believe that you are forgetting to actually do the upload, the code igniter documentation might help:
http://www.codeigniter.com/user_guide/libraries/file_uploading.html
With this correctly implemented, I think your code should look something similar to:
function add_item(){
$this->output->set_status_header(200);
$this->output->set_header('Content-Type: application/json');
$itemId = $this->input->post('itemId');
$itemImage = $this->input->post('itemImage');;
$config['upload_path'] = realpath(APPPATH.'../assets_main/img/item/');
$config['allowed_types'] = 'jpg|jpeg';
$config['max_size'] = '100';
$config['max_width'] = '200';
$config['max_height'] = '200';
$file_name = $config['file_name'] = md5(uniqid(mt_rand()));
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
//THE MISSING LINE
if($this->upload->do_upload()){
//THE FILE HAS NOW BEEN UPLOADED
$data = array('upload_data' => $this->upload->data());
$jdata['message'] = "Thank you for purchasing our item!";
$jdata['result'] = "SUCCESS";
echo json_encode($jdata);
exit();
}else{
//NO FILE UPLOADED
$jdata['result'] = "FAILED";
$jdata['message'] = "upload error.";
$jdata['field'] = "itemImage";
echo json_encode($jdata);
exit();
}
}
My initial thinking, having used CI and tried to do this same thing, is that you can't do file uploads via AJAX without a special plugin such as this:
http://malsup.com/jquery/form/
Specifically, this file upload portion:
http://malsup.com/jquery/form/#file-upload
Simply trying to send a post with the val of a file input will not work, I don't believe - though maybe more modern browsers are able to handle that now.

Codeigniter File Upload Custom Error Messages

I'm new to Codeigniter's Upload library, but I am familiar with the standard form library. My aim is to instead of use the standard upload library error messages (example: The file you are attempting to upload is larger than the permitted size.) use my own error messages.
In the standard form validation I could use the following code:
$this->form_validation->set_message('required', 'The %s is a required field. Please ensure this field contains the relevant data before continuing.');
However this method for the Upload Library doesn't seem to be the same as i'm attempting to instead of outputting the standard 'max_size' (upload form config rule) error message i want to use my own that actually includes the max size.
I was unable to find anything on this through Codeigniter's documentation, I will show you the code i am using in both my controller and view incase it is of any help:
controller:
$this->form_validation->set_rules('userfile', 'New Image', 'trim|callback_valid_upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$data['upload_data'] = '';
if (!$this->upload->do_upload('userfile')) {
$this->data['error'] = $this->upload->display_errors('<p>', '</p>');
} else { //else, set the success message
$this->data['success'] = "Upload success!";
$this->data['upload_data'] = $this->upload->data();
}
view (to output errors):
if (isset($upload_data)) {
foreach($upload_data as $key => $value) { ?>
<li><?=$key?>: <?=$value?></li>
<?php
}
}
So in short where i have my config items such as $config['max_size'] = '1'; in my controller i would like to set and error message for it and this doesn't seem to work: $this->form_validation->set_message('max_size', 'The file you have uploaded exceeds the %s MB file size.');
Thanks
You could try and example some thing like this for custom error messages.
if(file_exists(dirname(FCPATH) . '/install/index.php')) {
$data['error_install'] = $this->lang->line('error_install');
} else {
$data['error_install'] = '';
}

Categories