Which file permission should I use for uploading and downloading files to a folder in codeigniter?
My whole project is been hosted on FileZilla.
NOTE: Uploading downloading works perfectly fine when website is hosted loacally.
Error only occurs when hosted through FileZilla.
My Upload/Download folder is present in root directory of codeigniter (Directory where Application folder is present).
Upload Controller Code
public function do_upload(){
$rti_details['rtino'] = $this->input->post("rtino");
$rtino_result = $this->rti_model->get_rti_details_by_rtino($rti_details['rtino']);
if(!$rtino_result){
$upload=$this->upload_file('rtifile',$this->input->post('rtino'));
if($upload)
{
$data = array('rti_no'=>$this->input->post('rtino'),
'filer_name'=>$this->input->post('filername'),
'filer_add'=>$this->input->post('fileradd'),
'city'=>$this->input->post('city'),
'state'=>$this->input->post('state'),
'pin_code'=>$this->input->post('pin_code'),
'rti_cat'=>$this->input->post('rti_cat'),
'rti_file'=>$upload['full_path'],
'filed_on'=>$this->input->post('filedon')
);
$this->rti_model->insert_rti($data);
}
$result = true;
}
else
$result = false;
if($result)
$this->session->set_flashdata("flashSuccess","RTI added successfully");
else
$this->session->set_flashdata("flashError","Error in adding RTI. This RTI Number Already Exist.");
redirect("rti/rti_file");
}
private function upload_file($name ='',$sno = 0)
{
if($name=='rtifile'){ $config['upload_path'] = 'assets/rti_uploads/rti_file/'; }
if($name=='coverletter'){ $config['upload_path'] = 'assets/rti_uploads/cover_letter/'; }
if($name=='fullreply'){ $config['upload_path'] = 'assets/rti_uploads/full_reply/'; }
$config['allowed_types'] = 'pdf';
$config['max_size'] = '2050';
if(isset($_FILES[$name]['name']))
{
if($_FILES[$name]['name'] == "")
$filename = "";
else
{
$filename=$this->security->sanitize_filename(strtolower($_FILES[$name]['name']));
$ext = strrchr( $filename, '.' );
if($name=='rtifile'){ $filename='RTI_'.$sno.'_'.date('YmdHis').$ext; }
if($name=='coverletter'){ $filename='COVER_'.$sno.'_'.date('YmdHis').$ext; }
if($name=='fullreply'){ $filename='FULLREPLY_'.$sno.'_'.date('YmdHis').$ext; }
}
}
else
{
$this->session->set_flashdata('flashError','ERROR: File Name not set.');
redirect('rti/rti_file');
return FALSE;
}
$config['file_name'] = $filename;
if(!is_dir($config['upload_path']))
{
mkdir($config['upload_path'],0777,TRUE);
}
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload($name))
{
$this->session->set_flashdata('flashError',$this->upload->display_errors('',''));
redirect('rti/rti_file');
return FALSE;
}
else
{
$upload_data = $this->upload->data();
return $upload_data;
}
}
From the documentation:
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.
http://www.codeigniter.com/user_guide/libraries/file_uploading.html#the-upload-directory
Best wishes,
Paul
Related
I'm having 2 codeigniter applications one of them in the root and the other is in a sub directory. I'm trying to upload files from the application in the sub sirectory the the images/artists folder in the root (in the main application) but I get
ERROR 404 Page Not Found: Images/artists
The upload destination folder does not appear to be writable.
I run this code in the controller which is used to upload in the sub directory application
if (file_exists('../images/artists')) {
echo 'directory exists - ';
if (!is_dir('../images/artists')) {
echo 'not a dir';
}
else{
echo 'it is a dir';
}
}
And I get "directory exists - it is a dir" and then run the upload code
$gallery_path = realpath(APPPATH . '../images/artists/');
$config['upload_path'] = $gallery_path;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = '20000';
$config['file_name'] = round(microtime(true) * 1000).'.jpg';
$this->load->library('upload', $config);
if ($this->upload->do_upload('img')) {
$phot_data = $this->upload->data();
$photo_name = $phot_data['file_name'];
$this->resizeImage($photo_name);
$artist_data['image'] = $config['file_name'];
}
//not used here but dows it override and trigger the error?
function do_upload() {
if ($_FILES['photos']['name'][0] != '') {
$name_array = array();
foreach ($_FILES as $key => $value)
$_FILES['userfile']['name'] = $value['name'];
$_FILES['userfile']['type'] = $value['type'];
$_FILES['userfile']['tmp_name'] = $value['tmp_name'];
$_FILES['userfile']['error'] = $value['error'];
$_FILES['userfile']['size'] = $value['size'];
$config['upload_path'] = realpath(APPPATH . 'images/artists/');
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2000';
$this->load->library('upload');
$this->upload->initialize($config);
$this->upload->do_upload();
$data = $this->upload->data();
$name_array[] = $data['file_name'];
}
redirect('admin/gallery');
}
I checked images and artists permissions and they are set to 777 Where's the issue then?
The first snippet only checks if the directory exists, but you want to confirm that it is writable (i.e. that you can put new files into it).
Check is_writable for more details. To fix the problem you'll need to run chmod 600 /path/to/images/artists on the server.
I have a form in CodeIgniter that allows the user to upload 2 separate files. At the backend I want these files to get stored in the different folder. In the controller i have written the upload code
public function upload()
{
/**Start uploading file**/
$config['upload_path'] = './assets/file/.';
$config['allowed_types'] = 'gif|jpg|png|doc|txt';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file'))
{
$error = array('error' => $this->upload->display_errors());
echo $error;
}
else
{
$data = $this->upload->data();
echo $file = $data['file_name']; //name of file
}
/**End uploading file**/
/**Start uploading img**/
$config2['upload_path'] = './assets/img/.';
$config2['allowed_types'] = 'gif|jpg|png|doc|txt';
$config2['max_size'] = 1024 * 8;
$config2['encrypt_name'] = TRUE;
$this->load->library('upload', $config2);
if (!$this->upload->do_upload('img'))
{
$error1 = array('error' => $this->upload->display_errors());
echo $error1;
}
else
{
$data1 = $this->upload->data();
echo $img = $data1['file_name']; //name of img
}
/**End uploading img**/
}
The images are getting uploaded but they are getting uplaoded to same folder. Can anyone please tell how i can make the files get saved in seperate folders
in the second load , you need to initialiaze the loaded library because the load method don't initialize it :
$this->upload->initialize($config2);
when I run it on localhost my csv uploading file is completely fine but when I host it in the web it will get some error. Its redirecting me to the csvindex.php I already check the columns in csv file
Here's my importcsv():
function importcsv($org, $course) {
$data['addressbook'] = $this->users_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'student_fname'=>$row['student_fname'],
'student_lname'=>$row['student_lname'],
'student_course'=>$row['student_course'],
'email'=>$row['email'],
'student_dept'=>$row['student_dept'],
'student_year'=>$row['student_year'],
'student_img'=>$row['student_img'],
'contact'=>$row['contact'],
'password'=>md5($row['password'])
);
$this->users_model->insert_csv($insert_data);
}
redirect('admin/colleges/show_students/'.$org.'/'.$course);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
Here's my get_addressbook():
function get_addressbook() {
$query = $this->db->get('tbl_students');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
Can someone help me with this please?
Check $file_path,the upload folder path in your server and check your upload folder permission – Sharmistha Das 2 hours ago
The error seems to be that your upload path either does not exist or does not have the right permissions.
Best way to solve it is to go in via FTP or SSH to create the "uploads" folder in your codeigniter root.
While uploading csv file iam saving that file in uploads folder if the file uplaoded successfully into database or not uploaded then also it should be deleted automatically from that folder.Can any one help me regarding this.
$data['error'] = '';
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '10000';
$this->load->library('upload', $config);
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
}
else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
$csv_array = $this->csvimport->get_array($file_path,'',FALSE,0,3,0,$cformat);
if ($csv_array) {
$successflag=true;
foreach ($csv_array as $row) {
$order = array(
'department'=>$row['Department'],
'gender'=>$row['Gender'],
);
$query = $this->db->query("select count(*) cnt from order_master where order_id='{$order['order_id']}' ");
$row = $query->first_row();
if(trim($order['order_id'] )!="" && $row->cnt==0 ) {
$this->masterorder_model->order($order);
}
else if ( $row->cnt>0) {
$successflag=false;
$this->flash->success("<h5><font color='red'>Found Duplicate Order Id'{$order['order_id']}' for order name '$oname'</font></h5>");
break;
}
}
if(!$successflag) {
$this->db->trans_rollback();
}
else {
$this->db->trans_commit();
$this->flash->success('<h5>Csv Data Imported Successfully.</h5>');
}
redirect(base_url().'masterorder/index');
}
else {
$this->flash->success('<h5><font color="red">Invalid file format.</font></h5>');
redirect(base_url().'masterorder/index');
}
}
}
Use unlink() to delete file after processing.
Deletes filename. Similar to the Unix C unlink() function. A E_WARNING
level error will be generated on failure.
you can use the file helper for the codeigniter.
So it would be like as below :
$this->load->helper("file");
delete_files($path);
Please visit this for more information.
You can use unlink('path/filename' )
i am using CI 2.1.0 and mysql database for one of my projects. i am facing a problem with my image uploading method. the image i am uploading should be saved in uploads directory and create a thumbnail version of the image and the image path should be saved in database.
the code i have done works fine but there is one problem that when i upload an image, in the upload directory i get two copies of the same image and in the thumbs directory a single copy of the uploaded image. i want to have only one copy of the image instead of those two copies .
here is my code->
model:
function do_upload() //to upload images in upload directory
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
$this->upload->do_upload();
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
return $image_data;
}
}
some please tell me why two copies of images are being uploaded.
there is anothe thing, i want images to be overwritten if an image with same name exists. i have changed the upload.php file inside system->libraries to this
public $overwrite = TRUE;
but it is not working. someone please help.
you are calling $this->upload->do_upload() twice ..
Please try this code
Warning : Untested
function do_upload()
{
$i=$this->db->get('portfolio')->num_rows();
$i=$i+1;
$image_path=realpath(APPPATH . '../uploads');
$config=array(
'allowed_types'=>'jpeg|png|gif|jpg',
'upload_path'=>$image_path,
'max_size'=>2097152,
'overwrite'=>TRUE,
'file_name'=>'_'.$i.'_'
);
$this->load->library('upload', $config);
if( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
return $error;
}
else
{
$image_data = $this->upload->data();
$config=array(
'source_image'=>$image_data['full_path'],
'new_image'=>$image_path.'/thumbs',
'maintain_ration'=>TRUE,
'width'=>150,
'height'=>100
);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
return $image_data;
}
}
I will give an alternate uploader class for handling file uploads properly. You can re use this code anywhere .
<?php
//Save file as Uploader.php
//File Uploading Class
class Uploader
{
private $destinationPath;
private $errorMessage;
private $extensions;
private $allowAll;
private $maxSize;
private $uploadName;
private $seqnence;
public $name='Uploader';
public $useTable =false;
function setDir($path){
$this->destinationPath = $path;
$this->allowAll = false;
}
function allowAllFormats(){
$this->allowAll = true;
}
function setMaxSize($sizeMB){
$this->maxSize = $sizeMB * (1024*1024);
}
function setExtensions($options){
$this->extensions = $options;
}
function setSameFileName(){
$this->sameFileName = true;
$this->sameName = true;
}
function getExtension($string){
$ext = "";
try{
$parts = explode(".",$string);
$ext = strtolower($parts[count($parts)-1]);
}catch(Exception $c){
$ext = "";
}
return $ext;
}
function setMessage($message){
$this->errorMessage = $message;
}
function getMessage(){
return $this->errorMessage;
}
function getUploadName(){
return $this->uploadName;
}
function setSequence($seq){
$this->imageSeq = $seq;
}
function getRandom(){
return strtotime(date('Y-m-d H:iConfused')).rand(1111,9999).rand(11,99).rand(111,999);
}
function sameName($true){
$this->sameName = $true;
}
function uploadFile($fileBrowse){
$result = false;
$size = $_FILES[$fileBrowse]["size"];
$name = $_FILES[$fileBrowse]["name"];
$ext = $this->getExtension($name);
if(!is_dir($this->destinationPath)){
$this->setMessage("Destination folder is not a directory ");
}else if(!is_writable($this->destinationPath)){
$this->setMessage("Destination is not writable !");
}else if(empty($name)){
$this->setMessage("File not selected ");
}else if($size>$this->maxSize){
$this->setMessage("Too large file !");
}else if($this->allowAll || (!$this->allowAll && in_array($ext,$this->extensions))){
if($this->sameName==false){
$this->uploadName = $this->imageSeq."-".substr(md5(rand(1111,9999)),0,8).$this->getRandom().rand(1111,1000).rand(99,9999).".".$ext;
}else{
$this->uploadName= $name;
}
if(move_uploaded_file($_FILES[$fileBrowse]["tmp_name"],$this->destinationPath.$this->uploadName)){
$result = true;
}else{
$this->setMessage("Upload failed , try later !");
}
}else{
$this->setMessage("Invalid file format !");
}
return $result;
}
function deleteUploaded(){
unlink($this->destinationPath.$this->uploadName);
}
}
?>
Using Uploader.php
<?php
$uploader = new Uploader();
$uploader->setDir('uploads/images/');
$uploader->setExtensions(array('jpg','jpeg','png','gif')); //allowed extensions list//
$uploader->setMaxSize(.5); //set max file size to be allowed in MB//
if($uploader->uploadFile('txtFile')){ //txtFile is the filebrowse element name //
$image = $uploader->getUploadName(); //get uploaded file name, renames on upload//
}else{//upload failed
$uploader->getMessage(); //get upload error message
}
?>