Note is that : All data is inserted properly.
But if i'm upload an image with the help of
$this->upload->do_upload();and validate id,
this is not properly working. can u suggest..
//Controller
public function saveEmployeea()
{
$config = [ 'upload_path'=>'./uploads',
'allowed_types'=>'gif|jpg|png|jpeg'];
$this->load->library('upload', $config);
$this->form_validation->set_rules('dept_name', 'Department', 'required');
$this->form_validation->set_rules('firstname', 'First Name','required');
$this->form_validation->set_rules('middlename', 'Middle Name','required');
$this->form_validation->set_rules('lastname', 'Last Name','required');
$this->form_validation->set_rules('gendar', 'Gendar','required');
$this->form_validation->set_rules('address1', 'Local Address','required');
$this->form_validation->set_rules('address2', 'Permant Address','required');
$this->form_validation->set_rules('nationality', 'Nationality','required');
$this->form_validation->set_rules('date_of_joining', 'Joinig Date','required');
$this->form_validation->set_rules('current_designation', 'Designation_Curnt','required');
// $this->form_validation->set_rules('profile_image', 'Please Upload image','required');
$this->form_validation->set_rules('prof_email_id', 'Professional Email Id','required|valid_email');
$this->form_validation->set_rules('personal_email', 'Personal Email Id','required|valid_email');
$this->form_validation->set_rules('personal_no', 'Personal Contact No','required');
$this->form_validation->set_rules('emergency_no', 'Emergency No','required');
$this->form_validation->set_rules('highest_qualification', 'Highest Qualificatio','required');
$this->form_validation->set_rules('year_of_passing', 'Year Of Passing','required');
$this->form_validation->set_rules('university', 'University','required');
$this->form_validation->set_rules('no_experience', 'No Experience','required');
$this->form_validation->set_rules('pre_compony', 'Previus Compony','required');
$this->form_validation->set_rules('pre_designation', 'Previus Designation','required');
$this->form_validation->set_rules('pre_organisation_location', 'Previus organisation_location','required');
if ( $this->form_validation->run() && $this->upload->do_upload())
{
$data = $this->input->post();
// insert images in data variables by using upload object oprater.
$upload_info = $this->upload->data();
//set path for images store
$path = base_url("uploads/".$upload_info['raw_name'].$upload_info['file_ext']);
$data['profile_image'] = $path;
// echo '<pre>';
// print_r($data);
// echo '</pre>';
// var_dump($data);
// exit();
// Load Model to Call Model class
$this->load->model('Loginm');
if($this->Loginm->insertEmployee($data))
{
$this->session->set_flashdata('employee_details','Employee Details Added Successfully');
}
else
{
$this->session->set_flashdata('employee_details','Failed To Added Employee Details.');
}
return redirect('Employee/EmployeeList');
}
else
{
$upload_error = $this->upload->display_errors();
$this->createEmployee();
}
}
// Model
public function insertEmployee($data)
{
return $this->db->insert('employee',$data);
}`enter code here`
Try this code
$config['upload_path'] = 'd:/www/project_name/uploads/'; //document root path
$config['allowed_types'] = 'jpg|gif|png';
$config['file_name'] = $_FILES['profile_image']['name'];
//load upload class library
$this->load->library('upload', $config);
if (!$this->upload->do_upload('profile_image'))
{
// case - failure
echo $this->upload->display_errors();
}
else
{
// case - SUCCESS
}
First,
$this->upload->do_upload('userfile')
here 'userfile' in the name attribute in the input element.
<form action="url" enctype="multipart/form-data" method="post">
<input type="file" name="userfile" accept="image/*">
make sure you use:
enctype="multipart/form-data"
or
CI 3 counterpart:
echo form_open_multipart();
second,
The Upload Directory
You’ll need a destination directory for your uploaded images. Create a directory at the root of your CodeIgniter installation called uploads and set its file permissions to 777.
you may have file permission issue in the upload directory that you set. You should set proper permissions to the upload directory.
References:
https://www.codeigniter.com/userguide3/libraries/file_uploading.html
Related
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.
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.
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());
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'] = '';
}