I am having problem dealing with File Uploads in CodeIgniter 2.2.
I am able to create its specific folder destination, but I am unable to upload the file that I have selected.
Here's my Controller:
function create_report()
{
if($this->session->userdata('logged_in'))
{
$this->create_model->set_report();
$this->session->set_flashdata('message', 'Success! You created a Report!');
#$redirect($_SERVER['HTTP_REFERER'], 'refresh');
}
else
{
$this->session->set_flashdata('message', 'Oops! You have to Login');
//If no session, redirect to login page
redirect('login', 'refresh');
}
}
and here is my Model:
function set_report()
{
if($this->session->userdata('logged_in'))
{
$session_data = $this->session->userdata('logged_in');
if($_FILES['userfile']['name'] != NULL)
{
$main_dir = './FILES/'.$this->input->post('patientname').'/';
// Check if User Folder is already created. Create New if none exist
if(!is_dir($main_dir)){
mkdir($main_dir, 0777);
}
$target_dir = './FILES/'.$this->input->post('patientname').'/'.$this->input->post('session_id').'/';
// Check if Session Folder is already created. Create New if none exist
if(!is_dir($target_dir)) {
mkdir($target_dir, 0777);
}
$config['upload_path'] = './FILES/'.$this->input->post('patientname').'/'.$this->input->post('session_id').'/';
$config['allowed_types'] = 'gif|jpg|png|docx|xlsx|doc|pdf|csv|zip|rar|7zip|ppt|pptx';
$this->load->library('upload', $config);
$data2 = array('upload_data' => $this->upload->data());
}
$data = array(
'session_id' => $this->input->post('session_id'),
'report_creator' => $session_data['username'],
'report_patientname' => $this->input->post('patientname'),
'report_patientid' => $this->input->post('patientid'),
'report_subject' => $this->input->post('subject'),
'report_description' => $this->input->post('description'),
'report_time' => $this->input->post('date'),
'report_date' => $this->input->post('time')
);
return $this->db->insert('session_reports', $data);
}
}
I've been trying to solve this and I haven't figure out the key.
I hope anyone could help me with this.
I believe, I have failed to initialize the config.
$this->upload->initialize($config);
That solved my problem. Thank you everyone
Remove this
$data2 = array('upload_data' => $this->upload->data());
and replace this to that
if (!$this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
Load Library
$this->load->library('upload', $config);
Alternately you can set preferences by calling the initialize() method. Useful if you auto-load the class:
$this->upload->initialize($config);
Codeigniter file Upload
Related
I'm trying to upload a file but I keep getting a "The upload path does not appear to be valid." error. The problem is the path I'm trying to upload to is in the directory just outside the current one. The current folder structure is as follows:
application
assets
- uploads
- profile_pictures
Admin
- application
- assets
I am attempting to upload a picture from the admin application into the 'assets/uploads/profile_pictures' folder which is in the main application root directory. The only issue is correcting the path.
Here's the code from the Controller:
public function update_image(){
$user_id= $this->input->post('user_id');
//$user_id=$this->input->post('user_id');
$query5 = $this->db->get_where('user_details', array('user_id' => $user_id));
$name_user = $query5->row()->name;
$name='profile_image_edit';
$user_img=$this->function->upload_profile_images(array($name), $name_user);
var_dump($user_img);
$this->db->set("image_path",$user_img);
$this->db->where("user_id",$user_id);
$update = $this->db->update("users");
if($update)
{
echo 'Profile Image Updated.';
}
else
{
echo 'Profile Image Update Failed.';
}
}
And here's the code from the Model:
public function upload_profile_images($names, $username)
{
$config['upload_path']='./assets/uploads/profile_pictures';
$config['allowed_types']='jpeg|jpg|png';
$path = $_FILES[$names[0]]['name'];
var_dump($names[0]);
var_dump($path);
$ste_d =date('YmdHis') . gettimeofday()['usec'];
$newName = str_replace("",'',str_replace("",'',"$ste_d.str_replace(" ",'_',str_replace(".","",pathinfo($path, PATHINFO_FILENAME)))."_muddy.")).pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $username ."_". $newName;
$this->upload->initialize($config);
$this->load->library('upload', $config['upload_path']);
$check = true;
for($i = 0; $i < count($names) && $check; $i++)
{
if ( ! $this->upload->do_upload($names[$i]))
{
$path='./assets/uploads/profile_pictures';
$this->load->helper("file");
$error = array('error' => $this->upload->display_errors());
var_dump($error);
// delete_files($path, true);
$check = false;
return false;
}
else
{
$data = array('upload_data' => $this->upload->data());
$check = true;
return 'assets/uploads/profile_pictures'.'/'.$data['upload_data']['file_name'];
}
}
}
How do I set a custom path so the file is always saved in the desired directory of assets/uploads/profile_pictures from the Admin application. Thanks for any help!
I have a following code in the Codeigniter controller to upload some files to "upload" folder in the remote ubuntu server. In this case there is created a new folder named as officer_id in the upload folder when upload files and should be applied 755 permissions to it. Otherwise rejected to upload the files.
public function addFiles()
{
$this->checkPermissions('add', 'officer');
$bc = array(array('link' => '#', 'page' => 'Attachments'));
$meta = array('page_title' => 'Officers - Files', 'bc' => $bc);
$this->data['officer'] = $this->Officer_model->getOfficer();
$this->form_validation->set_rules('officer', "Officer", 'required');
if ($this->form_validation->run() == true) {
$files = $this->multi_upload($_FILES['file'], './uploads/' . $this->input->post('officer'));
if (!empty($files)) {
foreach ($files as $fname) {
$fdata[] = array(
'officer' => $this->input->post('officer'),
'file_name' => $fname,
'status' => 1,
);
}
if ($this->db->insert_batch('tbl_officer_files', $fdata)) {
$this->session->set_flashdata('message', 'Officer Attachments Updated Successfully ..!!');
redirect('officer/addFiles');
} else {
$this->session->set_flashdata('message', 'Officer Attachments Updation Failed ..!!');
redirect('officer/addFiles');
}
}
}
$this->render('officer/addFiles', $meta, $this->data);
}
public function saveUpload()
{
$this->multi_upload($_FILES['file']);
if ($this->upload->do_upload('file')) {
$data = array('upload_data' => $this->upload->data());
$inputFileName = './uploads/' . $data['upload_data']['file_name'];
echo json_encode(array('success' => 'Files have been uploaded successfuly ..!!'));
} else {
$error = array('error' => $this->upload->display_errors());
echo json_encode($error);//array('error' => 'You are not allowed to upload such a file.',
}
}
How can I modified my code to enable this (Like chmod ......) ? Can anyone help ?
You can use chmod("test.txt",0755); to update the permission on file after uploading.
You can do this step by step as follow.
//this function returns uploaded file path
$uploadedd_file = file_upload_function(...);
if(!file_exists($uploadedd_file)){
die('Error in uploading file');
}
// Setting file permission
$set_permission = chmod($uploadedd_file,0755);
if(!$set_permission){
// delete file if permission is not set
unlink($uploadedd_file);
}
// optional step to validate
$new_permission = substr(sprintf('%o', fileperms($uploadedd_file)), -4);
echo "all good goes here, file uploaded and permission is set to " . $new_permission;
Read more about chmod: https://www.w3schools.com/php/func_filesystem_chmod.asp
https://www.php.net/manual/en/function.chmod.php
I hope this works, let me know.
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 want to upload a file in a certain file if a file is chosen from the input file tag
<input name="file1" type="file" id="addimage1">
I want to know how to deal it in models. I want to send the link of the image to the database.
When I was not using code-igniter I was doing this:
if(!empty($_FILES['file1']['name']) ) {
move_uploaded_file($_FILES["file1"]["tmp_name"],'assets/results/'.$myid.'/'. $_FILES["file1"]["name"]);
$link1='assets/results/'.$myid .'/' . $_FILES["file1"]["name"];
}
How can I do this in Code-igniter.
As user guide states:
//after uploading config
if ( ! $this->upload->do_upload('userfileinputname'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
//here add to db
$this->file_model->add_link_to_db($data['filename']);
$this->load->view('upload_success', $data);
}
}
And inside your model:
public function add_link_to_db($filename) {
return $last_id = $this->db->insert('mytable', ['name'=>$filename]);
}
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());