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
}
?>
Related
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);
I'm trying to create a image upload function for my e-commerce website. This is the function I used to upload files,
Image upload function
private function upload_product_image($name, $file) {
$this->load->library('upload');
$dir = $name;
if (!is_dir('store/' . $dir)) {
mkdir('store/' . $dir, 777, true);
}
$config['upload_path'] = './store/' . $dir . '/';
$config['allowed_types'] = 'jpg|png';
$config['encrypt_name'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload($file)) {
return null;
} else {
if (is_file($config['upload_path'])) {
chmod($config['upload_path'], 777);
}
$ud = $this->upload->data();
$source = $ud['full_path'];
$destination = $ud['full_path'];
$image = imagecreatefromjpeg($source);
imagejpeg($image, $destination, 75);
return $config['upload_path'] . $ud['file_name'];
}
}
Save product
public function save_product(){
*** other code ****
$dir = date('Ymdhis');
$dir = url_title($dir, 'dash', true);
$this->upload_product_image($dir, 'add-product-image1'),
*** other code ****
}
There are couple of issues when running this function,
Image is not uploaded in first attempt ( Add new product )
But It created the product folder
If I update the product images It is working fine.
If you could show me, what is the wrong with this code It'll be really helpful.
Thank you so much
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
I want to upload PDF file as well as image file with on one do_upload
I want to upload two different files in two different directory by using codeigniter. I wrote the following code in my model. but it will upload only the first image.
if($_POST){
if($_FILES['productimage']['name']){
$img = $_FILES['productimage']['name'];
$config['upload_path'] = './uploads/products/';
$config['allowed_types'] = 'png|jpg|gif|bmp';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('productimage'))
{
$errors = array('error' => $this->upload->display_errors());
$img="";
}
else
{
$data =$this->upload->data();
$img=$data['file_name'];
//print_r($img);die;
}
}else{
$img=$this->input->post('image_old');
}
if($_FILES['productpdf']['name']){
$img = $_FILES['productpdf']['name'];
$config['upload_path'] = './uploads/products/';
$config['allowed_types'] = 'png|jpg|gif|bmp|pdf';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload('productpdf'))
{
$errors = array('error' => $this->upload->display_errors());
$pdf="";
}
else
{
$data =$this->upload->data();
$pdf=$data['file_name'];
}
}else{
$pdf=$this->input->post('pdf_old');
}
// print_r($img);print_r($pdf);die;
$title = $this->input->post('productname');
$content = $this->input->post('description');
$status = $this->input->post('status');
$this->db->where('product_id', $id);
$this->db->update('products',array('product_name'=>$title,'product_content'=>$content,'product_image'=>$img,'product_file'=>$pdf,'product_status'=>$status));
$this->db->where('product_id',$id);
$this->db->delete('products_filter');
$filters= $_POST['filter'];
foreach ($filters as $value)
{
$this->db->insert('products_filter',array('product_id' => $id,'products_search_id'=>$value));
}
return ($this->db->affected_rows() != 1)? false:true;
}else{
redirect(base_url('admin/products/product-list/'.$redirectid));
}
}
Please check my code
this code to handle pdf or images file upload in different directory
<?php
if($_POST){
if($_FILES['productimage']['name'])
{
$custom_file_name = $_FILES['productimage']['name'];
$file_ext = end(explode('.', $custom_file_name));
if($file_ext=='pdf')
{
$upload_path_directory='./uploads/products/pdf/';
$file_field_name="productimage";
}
else{
$upload_path_directory='./uploads/products/images/';
$file_field_name="productpdf";
}
$config['upload_path'] = $upload_path_directory;
$config['allowed_types'] = 'png|jpg|gif|bmp|pdf';
$config['overwrite'] = TRUE;
$this->load->library('upload',$config);
if(!$this->upload->do_upload("$file_field_name"))
{
$errors = array('error' => $this->upload->display_errors());
$custom_file_name="";
}
else
{
$data =$this->upload->data();
$custom_file_name=$data['file_name'];
}
?>
First to make sure to upload library libraries and form validation if don't know where to set libaray will mention below*
$this->load->libaray("upload");
$this->load->libaray("form_validation");
to add this code in if condition
I am trying to upload a zipped file using codeigniter framework with following code
function do_upload()
{
$name=time();
$config['upload_path'] = './uploadedModules/';
$config['allowed_types'] = 'zip|rar';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_view', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->library('unzip');
// Optional: Only take out these files, anything else is ignored
$this->unzip->allow(array('css', 'js', 'png', 'gif', 'jpeg', 'jpg', 'tpl', 'html', 'swf'));
$this->unzip->extract('./uploadedModules/'.$data['upload_data']['file_name'], './application/modules/');
$pieces = explode(".", $data['upload_data']['file_name']);
$title=$pieces[0];
$status=1;
$core=0;
$this->addons_model->insertNewModule($title,$status,$core);
}
}
But the main problem is that when extract function is called, it extract the zip but the result is empty folder. Is there any way to overcome this problem?
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);//to get the file type
$zip->close();
try this :
<?php
exec('unzip filename.zip');
?>
Hmm.., I think you set an incorrect path of your uploaded zip file OR your destination path ('./application/modules/') is incorrect.
Try this :
$this->unzip->extract($data['upload_data']['full_path'], './application/modules/');
I use this -> $data['upload_data']['full_path'], to make sure that it's a real path of the uploaded file.
Hope it helps :)
same problem i faced few min back.if you observe carefully you find
please copy zip file and paste to folder contain programe file(.php) after that you
i think file is not store in temp folder.
if(preg_match("/.(zip)$/i", $fileName))
{
$moveResult= move_uploaded_file($fileTmpLoc, $fileName);
if($moveResult == true)
{
$zip = new ZipArchive;
$res = $zip->open($fileName);
if($res==TRUE)
{
$zip->extractTo($path.$fileName);
echo "<pre>";
print_r($zip);
$zip->close();
} else {
echo 'failed';
}
}
unlink($fileName); // Remove the uploaded file from the PHP temp folder
//exit();
}`
class Upload extends CI_Controller {
function __construct(){
parent::__construct();
// load ci's Form and Url Helpers
$this->load->helper(array('form', 'url'));
}
function index(){
$this->load->view('upload_form_view', array('error' => ' ' ));
}
function file_upload(){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'zip';
$config['max_size'] = '';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload()){
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form_view', $error);
}else{
$data = array('upload_data' => $this->upload->data());
$zip = new ZipArchive;
$file = $data['upload_data']['full_path'];
chmod($file,0777);
if ($zip->open($file) === TRUE) {
$zip->extractTo('./uploads/');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
$this->load->view('upload_success_view', $data);
}
}
}
In case anyone comes here for same question, just add chmod($file,0777); to the original code posted yetAnotherSE. That solves the issue of empty files.