How to use uniqid in for loop? - php

I want to upload multiple photos but when I create an uniqid, the photos look the same uniqid. How can I get around this?
for($i=0;$i<$countfiles;$i++){
$_FILES['files']['name'] = $files['galeri']['name'][$i];
$_FILES['files']['type'] = $files['galeri']['type'][$i];
$_FILES['files']['tmp_name'] = $files['galeri']['tmp_name'][$i];
$_FILES['files']['error'] = $files['galeri']['error'][$i];
$_FILES['files']['size'] = $files['galeri']['size'][$i];
$config['upload_path'] = "uploads/urunler/galeri/";
$config["allowed_types"] = "jpg|jpeg|png";
$config['max_size'] = '5000';
$config['file_name'] = uniqid().$_FILES['files']['name'];
$this->load->library('upload', $config);
if($this->upload->do_upload('files')){
$uploadData = $this->upload->data();
$filename = $uploadData['file_name'];
$galeri_arr['filenames'][] = $filename;
}
}
Result:
{
0: "5f6fd81e54f1bimg52.jpg",
1: "5f6fd81e54f1bimg521.jpg"
}

For generate unique file name best way is use timestamp in file name with uniqid().
$config['file_name'] = uniqid().time().$_FILES['files']['name'];

Related

How to encrypt image name and save into database?

I can save the image name into database without any problem but when I try to encrypt the name only the image path gets the encrypted name but the database not
public function fileUpload(){
$clientes = $this->pm->getAllProducts();
foreach ($clientes as $cliente) {
$teste = $cliente->id;
}
if(!empty($_FILES['file']['name'])){
// Set preference
$config['upload_path'] = "uploads/";
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['max_size'] = '5024'; // max_size in kb
$config['encrypt_name'] = TRUE;
$config['file_name'] = $_FILES['file']['name'];
$this->upload->initialize($config);
//Load upload library
$this->load->library('upload',$config);
$data = array(
'pub_id' => $teste,
'url' => $_FILES['file']['name']
);
$this->pm->addProduct($data);
// File upload
if($this->upload->do_upload('file')){
// Get data about the file
$uploadData = $this->upload->data();
}
}
}
You can encrypt file name with config
$config['encrypt_name'] = TRUE;
Or
$file= uniqid().time().$_FILES["file"]['name'];
$config['file_name'] = $file;

Codeigniter obtain image name for multiple files

I have some code that i am using to upload multiple images i a form. I am uploading and renaming the images like this
//Obtain Picture
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 5000;
$config['max_width'] = 2000;
$config['max_height'] = 2000;
$rand_name = 'vehicles'.rand(321,8999).'_'.time();
$config['file_name'] = $rand_name;
$this->load->library('upload', $config);
$this->upload->do_upload('logbook');
$this->upload->do_upload('inrep');
$this->upload->do_upload('insurance');
$this->upload->do_upload('vp');
$data = array('upload_data' => $this->upload->data());
the form names for the multiple uploads which are unrelated are as follows logbook,inrep,insurance and vp
The code above uploads the files and renames them but i would like to obtain the new names of the files given the form name of the fields.
Right now, the files are uploaded and renamed but i cant they are from which field name.
You can get new file name using
$this->upload->data();
This will return details of uploaded files.
So you can do it like
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png|pdf';
$config['max_size'] = 5000;
$config['max_width'] = 2000;
$config['max_height'] = 2000;
$rand_name = 'vehicles'.rand(321,8999).'_'.time();
$config['file_name'] = $rand_name;
$this->load->library('upload', $config);
$this->upload->do_upload('logbook');
$logbook = $this->upload->data();
$logbook_new_filename = $logbook['file_name'];
$this->upload->do_upload('inrep');
$inrep = $this->upload->data();
$inrep_new_filename = $inrep['file_name'];
$this->upload->do_upload('insurance');
$insurance= $this->upload->data();
$insurance_new_filename = $insurance['file_name'];
$this->upload->do_upload('vp');
$vp= $this->upload->data();
$vp_new_filename = $vp['file_name'];
I haven't tested it. But I use like this to get uploaded filename.Hope it will help.

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;

Dynamically Codeigniter Image Upload Rename

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;

Codeigniter Rename file on upload

I'm trying to add time as the prefix of the image name along with the original name when uploading, But I couldn't figure it out. Please help me with the following code to add a prefix to my original file name when uploading.
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = 'Public/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
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);
}
}
}
?>
You can encrypt file name with use of CI native option:
$config['encrypt_name'] = TRUE;
OR
You can do it with your own code:
$new_name = time().$_FILES["userfiles"]['name'];
$config['file_name'] = $new_name;
For some reasons, consecutive calls to the do_upload function doesn't work. It sticks to the first filename set by the first function call
$small_photo_url = $this->upload_photo('picture_small', $this->next_id.'_small ');
$medium_photo_url = $this->upload_photo('picture_medium', $this->next_id.'_medium');
$large_photo_url = $this->upload_photo('picture_large', $this->next_id.'_large ');
The filenames will all be "00001_small", "00001_small1", "00001_small2"
given the following configurations
function upload_photo($field_name, $filename)
{
$config['upload_path'] = 'Public/uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '1024';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $filename;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())...
I think it's because this line doesn't work the second time you call it. It does not set the configurations again
$this->load->library('upload', $config);
==========================================================================
Solution to the problem faced during consecutive do_upload function calls:
// re-initialize upload library
$this->upload->initialize($config);
/* Conf */
$new_name = time().$_FILES["userfiles"]['name'];
$config['file_name'] = $new_name;
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '';
$config['max_width'] = '';
$config['max_height'] = '';
$config['file_ext_tolower'] = TRUE;
/* Load the upload library */
$this->load->library('upload', $config);
For what you are exactly looking for, this worked for me:
$path = $_FILES['image']['name'];
$newName = "<Whatever name>".".".pathinfo($path, PATHINFO_EXTENSION);
when you use do_upload() function its rename file name if already exists and upload file
System->libraries->Upload.php
default function of do_upload() return true or false
replace
return $this->upload_path.$this->file_name;
and in another file
<input type='file' name='userfile'/>
<?php
$upload_file_name = $this->upload->do_upload('userfile');
$finalname;
if (!$upload_file_name) {
$finalname = 'default.png';
} else {
$split_data_upload_file_name = explode("/", $upload_file_name);
foreach ($split_data_upload_file_name as $i => $value) {
$finalname = $value;
}
}
?>
$config['file_name'] = $new_name;
Just add it align with the config codes.
This should be after the upload.
Process the filename you want here:
$a=$this->upload->data();
rename($a['full_path'],$a['file_path'].'file_name_you_want');
Try This:
$config['file_name'] = "yourCustomFileName";
If your $config is with this code: $config['encrypt_name'] = TRUE;
the name of your file will be forced to rename with a encrypt name, just remove the code.
Solution 1: Upload file with new customized and specific name (Note: this answer is applicable when you are submitting a unique name of a record, for example student name is a unique value in a record then you will use $_POST['student_name'])
$config['file_name'] = str_replace(' ', '_', $_POST['anyUniqueValue']);
//any Other unique value that you are using to submit with this file
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;
Solution 2: Upload file with new unique name
$config['file_name'] = time();
$config['upload_path'] = './folderName/';
$config['encrypt_name'] = FALSE;
Solution 3: Upload file with new unique name using codeigniter's default option
$config['encrypt_name'] = TRUE;
if you do multiple file upload, maybe you can try update library Upload.php
on system/libraries/Upload.php. On function do_upload()
$this->file_name = $this->_prep_filename($_file['name']);
to
$this->file_name = time().'_'.$this->_prep_filename($_file['name']);

Categories