//views/myproject/testupload.php
<a class="btn pull-right btn btn-primary"
href="<?= site_url("myproject/upload/") ?>"><?= lang('upload') ?></a>
//views/myproject/upload.php
<?php echo form_open_multipart(site_url('myproject/do_upload'));?>
<?=form_line('', form_upload('userfile', $this->form_validation->set_value('userfile')));?>
<?=form_submit('upload', lang('action_upload'), 'class="btn btn-primary"');?>
<?php echo form_close();?>
//Controller/myproject/test.php
public function upload()
{
$this->output->view('analytics/kysim/upload');
}
public function do_upload()
{
$config['upload_path'] = 'C:/test/';
$config['allowed_types'] = 'txt';
$this->load->library('upload', $config);
$name_file = $_FILES['userfile']['name'];
if ( ! $this->upload->do_upload($name_file))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die();
//$this->load->view('upload', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
var_dump($data);
die();
//$this->load->view('success', $data);
}
}
I am not able to upload a file to a specified location(C://test).var_dump($name_file) displays the uploaded file name.
$this->upload->do_upload($name_file) returns false and so var_dump($error) displays the error message "error" => "<p>You did not select a file to upload.</p><p>You did not select a file to upload.</p>""
Any help on uploading the file to specified location(C://test) would be appreciated.
Hope this will help you :
Note : make sure your c drive has test folder which in turn have writable permission
Your do_upload method should be like this :
public function do_upload()
{
$config['upload_path'] = 'C:\test\\';
$config['allowed_types'] = 'txt';
$this->load->library('upload', $config);
if (! empty($_FILES['userfile']['name']))
{
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
var_dump($error);
die();
}
else
{
$data = array('upload_data' => $this->upload->data());
var_dump($data);
die();
}
}
}
Your form should be like this :
<?php
echo form_open_multipart('myproject/do_upload');
echo form_line('', form_upload('userfile', $this->form_validation->set_value('userfile')));
echo form_submit('upload', lang('action_upload'), 'class="btn btn-primary"');
echo form_close();
?>
For more : https://www.codeigniter.com/user_guide/libraries/file_uploading.html
This tutorial might help you:-
https://www.formget.com/codeigniter-upload-image/
Related
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);
}
}
I'm trying to add a file upload function in my website using codeigniter's upload library.
here's my view file (display.php):
<html>
<body>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" name="filename" />
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
</body>
</html>
and here's the controller:
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload');
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('filename'))
{
echo 'error!';
}
else
{
echo 'success!';
}
echo 'end upload';
}
$this->load->view('display', $this->data);
}
but the code seems to stop after $this->upload->initialize($config); the file was not uploaded, and there was no message at all. only the 'start upload' message appeared; the echo 'success' , echo 'error' , and echo 'end upload' do not appear.
why is that? can anyone help me??
Late from party, but maybe this can help somebody with same problem. Please try this:
Views:
<?php echo form_open_multipart('test/upload');?>
<input type="file" name="photo">
<?php echo form_close();?>
Controller:
class Test extends CI_Controller {
function upload() {
$config = array(
'upload_path' => './assets/upload/',
'allowed_types'=> 'gif|jpg|png',
'encrypt_name' => TRUE // Optional, you can add more options as need
);
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('photo')) {
echo '<pre>';
print_r($this->upload->display_errors());
exit();
} else {
echo '<pre>';
print_r($this->upload->data());
exit();
}
}
}
Inside views i recomended use this function form_open_multipart('ctrl/method') but if you prefer using HTML5 forms, just be sure correct the attributes in form like this.
<form action="<?=site_url('ctrl/method')?>" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="photo">
</form>
More preferences in $config['..'] can you find in documentation CodeIgniter https://codeigniter.com/user_guide/libraries/file_uploading.html
Try like this....
public function testupload()
{
if ( ! empty($_FILES))
{
echo 'start upload';
$config['upload_path'] = './assets/img/tempfile/';
$this->load->library('upload',$config);
if ( ! $this->upload->do_upload('filename'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('display', $error); //loads the view display.php with error
}
else
{
echo 'success!';
}
echo 'end upload';
$data = array('upload_data' => $this->upload->data());
$this->load->view('display', $data); //loads view display.php with data
}
}
change from
$config['upload_path'] = './assets/img/tempfile/';
to
$config['upload_path'] = 'assets/img/tempfile/';
i check this code this work perfect
simply add this line
$config['allowed_types'] = 'png|gif|jpg|jpeg';
$config['max_size'] = '7000';
after this
$config['upload_path'] = './assets/img/tempfile/';
or you can also set this in view page
action="<?php echo base_url('YourController/testupload');?>"
this is due to php server version and it's option.
1).go to cpanel account
2).click "select php version", in the software section.
3).tap the "fileinfo" chexbox in the php option and save.
now you can upload file perfectly.
Same issue as described. I have fixed it using the following: Open the file system/libraries/Upload.php go to function validate_upload_path() and add the command return TRUE; as a last line inside this function. Save and try again.
use this for image upload:
$valid_extensions = array('jpeg', 'jpg', 'png');
if ($_FILES['filename']['error'] == 0) {
$img = $_FILES['filename']['name'];
$tmp = $_FILES['filename']['tmp_name'];
$ext = strtolower(pathinfo($img, PATHINFO_EXTENSION));
if (in_array($ext, $valid_extensions)) {
$path = "./assets/img/tempfile/" . strtolower($img);
if (move_uploaded_file($tmp, $path)) {
$_POST['filename'] = $path;
}
}
}
use insert query to insert file :
$this->db->insert('table_name', $_POST);
Having the same problem on macOS. It seems that if you are not the "main" user of your laptop/pc, the default permission is "Read Only". You must change it to "Read & Write".
Right click on the folder
Get Info
Sharing and permissions
Change 'Read Only' to 'Read & Write'
add allowed file type parameter in config
$config['allowed_types'] = 'gif|jpg|png';
your code is missing the following,
$this->load->library('upload',$config);
Recorrect it by rewriting the above code.
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);
When I am running on localhost, it is fine. After uploaded on server.one error thrown-i.e.
The upload destination folder does not appear to be writable.
This is my controller-
function do_upload()
{
$path = './uploads/';
chmod($path,0777);
$config['upload_path'] = $path;
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$this->load->library('form_validation');
$data = array('upload_data' => $this->upload->data());
$pic_path= 'uploads/'.$data['upload_data']['file_name'];
$this->form_validation->set_rules('txt_title','Title','trim|required|xss_clean');
$this->form_validation->set_rules('category', 'Select Category', 'callback_select_validate');
$this->form_validation->set_rules('description','Description','trim|required|xss_clean');
if($this->form_validation->run() == FALSE)
{
redirect('upload');
}
else{
$title =mysql_real_escape_string(htmlentities($this->input->post('txt_title')));
$category = $this->input->post('category');
$description = mysql_real_escape_string(htmlentities($this->input->post('description')));
$this->load->model('user');
$suc_mesg=$this->user->insertPic($pic_path,$category,$title,$description);
$this->load->view('upload_success', $suc_mesg);
}
}
}
This is my view page-
<?php
echo $error;
echo form_fieldset('Upload Category Pics');
echo form_open_multipart('upload/do_upload');
echo '</br>';
echo form_label('Title','title');
echo '<input type="text" size="30" name="txt_title" placeholder="Enter title to pic"/>';
echo '</br></br>';
echo form_label('Choose Category Pics', 'category');
$options = array(
'null' => '--Please Select--',
1 => 'Technology',
3 => 'Entertainment',
2 => 'Politics',
4 => 'Sports'
);
echo form_dropdown('category', $options, 'category');
echo "<br></br>";
echo form_label('Description','description');
$data = array(
'name' => 'description',
'id' => 'description',
'placeholder' => 'Enter description',
'rows' => '5',
'cols' => '40',
);
echo form_textarea($data);
echo '</br></br>';
echo form_label('Browse Pics','pics');
echo '<input type="file" name="userfile" size="20" />';
echo "<br></br>";
echo '<input type="submit" value="upload" />';
echo '</form>';
echo form_fieldset_close();
?>
I'm unable to find my bug,where exactly am wrong. is there anybody ready to help me plz?
If the folder is for loading files by users than permisision 777 is required.
It's up to you to validate what files are loaded through upload script. Also you can use .htaccess to alow or not alow certain files to be executed from that directory.
The documentation for upload in codeigniter it's pretty simple and intuitive. Also here you can look at some ways to validate the type of files that are uploaded http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html
I changed my uploads folder on web server as writable, so now it seems working.
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('', '');