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]);
}
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.
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
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
I have a form with few inputs and a file input.
I want to check whethere the file input is empty or not.
If it is empty do not try to upload, if it is not then try to upload it.
I tried something like this:
$upld_file = $this->upload->data();
if(!empty($upld_file))
{
//Upload file
}
you use codeigniter's file uploader class... and call $this->upload->do_upload(); in a conditional statement ahd check if its true.
<?php
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);
}
The user_guide explains this in detail: http://codeigniter.com/user_guide/libraries/file_uploading.html
However,
if you are dead set on checking whether a file has been "uploaded" aka.. submitted BEFORE you call this class (not sure why you would). You can access PHPs $_FILES super global.. and use a conditional to check if size is > 0.
http://www.php.net/manual/en/reserved.variables.files.php
Update 2: This is actual working code, i use it on an avatar uploader myself using CI 2.1
<?php
//Just in case you decide to use multiple file uploads for some reason..
//if not, take the code within the foreach statement
foreach($_FILES as $files => $filesValue){
if (!empty($filesValue['name'])){
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);
}
}//nothing chosen, dont run.
}//end foreach
Probably do need more info. But basically, using the codeigniter upload class do something like this:
$result = $this->upload->do_upload();
if($result === FALSE)
{
// handle error
$message = $this->upload->display_errors();
}
else
{
// continue
}
There is a lot of functionality in codeigniter, probably don't need to re-invent the wheel here.