Dynamically Codeigniter Image Upload Rename - php

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;

Related

adding timestamp while uploading image file is not working

I am developing a ad site that anyone able to upload 3 images.
So I am coding to upload that 3 images by adding timestamp in front of their file name to make them unique. I use codeigniter framework and attaching the code below.
when I submitting form data, localhost server shows that images have been saved correctly with some code infornt of image filename. But problem is there are no images saved in relevant image folder in that name and I cannot retrieve that images in next preview advertisement page.
I don't know much about php or codeignitor. Your help is highly appreciated.
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 5120;
$this->load->library('upload',$config);
$this->upload->initialize($config);
if (!$this->upload->do_upload()){
$errors = array('error' => $this->upload->display_errors());
$post_image = 'no_image.jpg';
}
else {
$data = array('upload_data' => $this->upload->data());
$post_image1 = time().$_FILES['userfile1']['name'];
$post_image2 = time().$_FILES['userfile2']['name'];
$post_image3 = time().$_FILES['userfile3']['name'];
}
$result = $this->post_model->adregister($post_image1,$post_image2,$post_image3);
You can append time to 'filename' in config of upload library
$config['file_name'] = time().$_FILES['userfile1']['name'];
Or if you want unique name for all files the simply add
$config['encrypt_name'] = TRUE;
then
$this->load->library('upload', $config);
Try this one:-
$path = pathinfo($_FILES["userfile1"]["name"]);
$image_path = $path['filename'].'_'.time().'.'.$path['extension'];
I've written a possible solution for your code. You haven't shared your full code so you'll have to fill in the gaps yourself and maybe make some changes here and there; Comments are mentioned wherever necessary. See if it helps you.
public function your_function_name(){
// your-code
// your-code
// check if file is uploaded in field1
if(!empty($_FILES['userfile1']['name'])){
// call function to upload file
$userfile1 = $this->upload_file('userfile1');
}
// check if file is uploaded in field2
if(!empty($_FILES['userfile2']['name'])){
$userfile2 = $this->upload_file('userfile2');
}
// check if file is uploaded in field3
if(!empty($_FILES['userfile3']['name'])){
$userfile3 = $this->upload_file('userfile3');
}
$result = $this->post_model->adregister($userfile1, $userfile2, $userfile3);
}
// function to upload file
function upload_file($filename){
$config['file_name'] = time().$_FILES[$filename]['name']; // append time to filename
$config['upload_path'] = './assets/images/adsimages';
$config['allowed_types'] = 'gif|jpg|jpeg|png|GIF|JPG|PNG|JPEG';
$config['max_size'] = 5120;
$this->load->library('upload', $config);
$this->upload->initialize($config);
$uploaded = $this->upload->do_upload($filename);
if ( ! $uploaded ){
$error = array('error' => $this->upload->display_errors());
$file = 'no_image.jpg'; // default file
}else{
$upload_data = $this->upload->data();
$file = $upload_data['file_name']; // uploaded file name
}
return $file; // return filename
}

Codeigniter: cannot upload files from subdirectory to main directory

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.

Rename image name after upload in codeigniter

I need to rename image name after upload because my requirement is I need to add id with it so it's possible after store image name in DB.
I have done code for uploading image with and without watermark into different folder but now I want to change it's name like:
$imageName = $imgId.''.randomstring.''.$ext;
I have tried with below code but same image stored in both folder with watermark. I want to store original image in original_image folder and with watermark image in watermark_folder. Please help me to resolve this issue.
$getImgs = $this->photographer_model->get_uploaded_image($result);
$getExt = substr($getImgs[0]['img_name'], strrpos($getImgs[0]['img_name'],'.')+0);
$randomStr = $this->generate_random_string(20);
$fileName = $result."-".$randomStr."".$getExt;
$originalImgPath = base_url()."assets/original_image/".$fileName;
$watermarkImgPath = base_url()."assets/watermark_image/".$fileName;
$uploadOrgImg = 'assets/original_image/'.$fileName;
$uploadWaterImg = 'assets/watermark_image/'.$fileName;
$updateImg = $this->photographer_model->update_img_path($result, $fileName, $originalImgPath, $watermarkImgPath);
if(file_exists('assets/original_image/'.$getImgs[0]['img_name']) || file_exists('assets/watermark_image/'.$getImgs[0]['img_name'])) {
unlink('assets/original_image/'.$getImgs[0]['img_name']);
unlink('assets/watermark_image/'.$getImgs[0]['img_name']);
$config1['upload_path'] = 'assets/original_image/';
$config1['allowed_types'] = 'jpeg|png|jpg|svg';
$config1['file_name'] = $fileName; // set the name here
$this->load->library('upload', $config1);
$this->upload->initialize($config1);
$this->upload->do_upload('image');
$config['upload_path'] = 'assets/watermark_image/';
$config['allowed_types'] = 'jpeg|png|jpg|svg';
$config['file_name'] = $fileName; // set the name here
$this->load->library('upload', $config);
$this->upload->initialize($config);
$this->upload->do_upload('image');
}
Update Your Code Below With this
$config1['upload_path'] = 'assets/original_image/';
$config1['allowed_types'] = 'jpeg|png|jpg|svg';
$config1['encrypt_name'] = TRUE;
And Update for the second one
$config['upload_path'] = 'assets/watermark_image/';
$config['allowed_types'] = 'jpeg|png|jpg|svg';
$config['encrypt_name'] = TRUE;

Codeigniter, how to save uploaded file to new folder?

I'm adding onto an admin CMS, and need image files uploaded to save to a separate folder I have specified. I can save them to a predefined folder of another controller, but how do I save them to the new folder I have created?
When I try, it doesn't allow it. I know it has something to do with routing, but where to I change codeigniter to allow that? I have looked in config/routes.php and don't see it listed there.
Thank you!
you can try this
function uploadFile($uploadFile,$filetype,$folder,$fileName='')
{
$resultArr = array();
$config['max_size'] = '1024000';
if($filetype == 'img') $config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['upload_path'] = './uploads/'.$folder.'/';
if($fileName != "")
$config['file_name'] = $fileName;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($uploadFile))
{
$resultArr['success'] = false;
$resultArr['error'] = $this->upload->display_errors();
} else {
$resArr = $this->upload->data();
$resultArr['success'] = true;
$resultArr['path'] = "uploads/".$folder."/".$resArr['file_name'];
}
return $resultArr;
}

Upload problem with PHP: Thumbnail picking up the image name

I have the following model(codeigniter) code to upload image and thumbnail.
However the result of image path becomes, images/comfort_big.jpg and images/comfort_big.jpg.jpg.
The thumbnail image picks up the name of image and add .jpg.
I am uploading images/confort_thumb.jpg for thumb.
Can anyone tell me what's wrong please?
if ($_FILES){
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '200';
$config['remove_spaces'] = true;
$config['overwrite'] = false;
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->load->library('upload', $config);
if (strlen($_FILES['image']['name'])){
if(!$this->upload->do_upload('image')){
$this->upload->display_errors();
exit();
}
$image = $this->upload->data();
if ($image['file_name']){
$data['image'] = "images/".$image['file_name'];
}
}
if (strlen($_FILES['thumbnail']['name'])){
if(!$this->upload->do_upload('thumbnail')){
$this->upload->display_errors();
exit();
}
$thumb = $this->upload->data();
if ($thumb['file_name']){
$data['thumbnail'] = "images/".$thumb['file_name'];
}
}
}
I had a quick look at File Uploading Class in the user guide
In the preferences tables it states:
Note:The filename should not include a file extension.
So my guess is that you get the user to name the file
$config['file_name'] = "User defined";
or remove the extension programmatically. Since you know and list the extensions already you could do
$types = array(".gif",".jpg",".png");
$image['file_name'] = str_replace($types , "", $image['file_name'] );
Your problem is that when you create a thumb you are passing the full image.
So it will add another extension to it.
Use Below code to remove extension from file name.
<?php
$filename=$image['file_name'];
$file_name_with_dot = substr($filename,0, strrpos($filename, '.') + 1);
$only_file_name = substr($file_name_with_dot,0,strlen($file_name_with_dot)-1);
?>
Now pass this $only_file_name variable to your thumb function..
It will be better to use automatic thumb creation from main image.
Hope this will help for you.

Categories