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
Related
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 am getting this error:
Could not open /home/Projectname/public_html/assets/uploads/empfiles/
The filetype you are attempting to upload is not allowed.
for reading! File does not exist.
Please help me to resolve this.
I am using Codeigniter version:2.1.4
I have tried this solutions also, but no changes I found.
Uploading in Codeigniter - The filetype you are attempting to upload is not allowed
Code goes here:
$filextesions = $fileparameters->file_extensions;
$path = $fileparameters->path_required;
$filename = $fileparameters->filename;
$inputfilename = $fileparameters->inputname;
$fileType = $fileparameters->$inputfilename['type'];
if($fileparameters->width=='')
{
$width = 0;
}
else
{
$width = $fileparameters->width;
}
if($fileparameters->height=='')
{
$height = 0;
}
else
{
$height = $fileparameters->height;
}
/** Checking for file existence **/
$file_exist= FCPATH.'assets/uploads/'.$path.'/'.$filename;
if(file_exists($file_exist))
{
/* Renaming the existed file name */
$newfilename = uniqid().$filename;
}else
{
$newfilename = $filename;
}
/** Conifgure File parameters **/
$config['upload_path'] = FCPATH.'assets/uploads/'.$path;
$config['allowed_types'] = $filextesions;
$config['file_name'] = $newfilename;
$config['remove_spaces'] = FALSE ;
$config['max_size'] = '0';
$config['max_width'] = $width;
$config['max_height'] = $height;
/** Intialising uploadbject **/
$this->upload->initialize($config);
/** Checking for File existence **/
if($this->upload->do_upload($inputfilename))
{
return $newfilename;
}
else
{
return $this->upload->display_errors();
}
Mime types for xlsx files
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip', 'application/vnd.ms-excel')
Advance thanks
I am uploading multiple dynamic images with codeigniter with the following code.
foreach ($_FILES as $key => $value) {
$imagePrefix = time();
if (!$this->upload->do_upload($key))
{
echo $errors = $this->upload->display_errors();
return '';
}
else
{
$imagename = $imagePrefix.$value['name'];
$insertImage = $this->db->query("Insert into `tbl_event_imges` (`iEventID`,`vImage`) values ('".$insertId."','".$imagename."')");
}
}
When I upload an image to the specific folder this works fine; the issue is if a user uploads an image having same name, then it will automatically rename the image and upload to the folder, but what I want is to rename it by adding $imagePrefix that I have added in else part of the code and then want to upload the image with this name. But this is not working with me..
Any suggestion please?
you need to provide configuration preferences to your upload function like so:
$imagePrefix = time();
$imagename = $imagePrefix.$value['name'];
$this->load->library('upload');
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['file_name'] = $imagename; // set the name here
$this->upload->initialize($config);
if (!$this->upload->do_upload($key)){
...
}else{
...
}
Source: http://www.codeigniter.com/user_guide/libraries/file_uploading.html?highlight=file%20upload#setting-preferences
Just alternative, you can use CI's rename function to rename after file uploaded.
$image = $this->upload->data();
$file_path = $image ['file_path'];
$file = $image ['full_path'];
$file_ext = $image['file_ext'];
$final_file_name = time() . $image['file_name'] . $file_ext;
only add below code and it run successfully and also set encrypt_name to false
$path = $_FILES['userfile']['name'];
$newName = "Add any name".".".pathinfo($path, PATHINFO_EXTENSION);
$config['file_name'] = $newName;
$config['encrypt_name'] = false;
I am really struggling with my CodeIgniter script for uploading, resizing and cropping profile images for users. In the end, I want to upload the image with an encrypted name, resize it and save it twice (once as a thumbnail and once as a medium sized image), and then delete the original file. However, I guess I'm really missing something, because I can't get the first upload resize process to work. I definitely have an error somewhere in the code (error to follow code), but I think I may have a gap in my understanding of the logic here. Who knows? Any feedback is extremely appreciated .
public function image() {
$config['upload_path'] = './temp_images/'; // This directory has 777 access
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '0'; // For unlimited width
$config['max_height'] = '0'; // For unlimited height
$config['encrypt_name'] = TRUE;
$config['remove_spaces'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$data['error'] = array('error' => $this->upload->display_errors());
$this->load->view('upload', $data);
}
else
{
$image_data_array = array('upload_data' => $this->upload->data());
foreach ($image_data_array as $image_data){
$raw_name = $image_data['raw_name'];
$file_ext = $image_data['file_ext'];
}
$file_name = $raw_name . $file_ext;
$image_path = 'temp_images/' . $file_name;
$new_path = 'image/profile/'; // This directory has 777 access
$config['image_library'] = 'gd';
$config['source_image'] = $image_path;
$config['new_image'] = $new_path;
$config['maintain_ratio'] = FALSE;
$config['width'] = 140;
$config['height'] = 140;
$config['quality'] = '80%';
$new_name = $new_path . $raw_name . $file_ext;
$this->load->library('image_lib', $config);
// The following is just to test that it worked:
if ( ! $this->image_lib->resize()) {
echo $this->image_lib->display_errors();
echo 'source: ' . $config['source_image'] . '<br />';
echo 'new: ' . $config['new_image'] . '<br />';
}
else {
echo "<img src='" . base_url() . $new_name . "' />";
}
$this->image_lib->clear();
}
}
The upload process works fine. Even the resizing worked when I just called $this->image_lib->resize(). It was when I tried the error-catching that it started yelling at me. I double-verified that both of the temp_images and image/profile have 777 permissions (as aforementioned, the upload and resize actually worked at one point). Here is the error produced:
Unable to save the image. Please make sure the image and file directory are writable.
source: temp_images/8ee1bab383cf941f34218f7535d5c078.jpg
new: image/profile/
Never really used CI before and can't see the details of your code.
First, check the permission that set on the folder - you are trying to upload to. Also try to use the full server path.
Second, see if you have PHP image extensions such as GD, ImageMagick enabled.
i've tried this tutorial
it works well for image upload and create thumbs folder for the resizing image...
Please update the new_image value by including the filename also.
$config['new_image'] = 'image/profile/' . $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
}
?>