-1

i have an algorithm to upload an image with automatically naming, but i give the name with id from database, but the data in database isn't exist yet, so i insert the data first, then i get the max id as name of image (you can find it out clearly in my attachment code below and id is auto-increment), and the problem is i think if the server get much request to upload image, the image will have wrong name or name with id that doesn't belong to it. is there best practice regard to my problem?? or you have better algorithm about it?? please help me

This code written in php with codeigniter

if(isset($_FILES['gambarProduk'])){
    $this->db->select_max('idProduk','maks');
    $this->db->insert('gambarProduk',array('idProduk'=>$this->db->get('produk')->result()[0]->maks));
    $config['upload_path']          = 'images/produk/';
    $config['allowed_types']        = 'gif|bmp|jpg|png|jpeg';
    $this->db->select_max('idGambar','maks');
   $config['file_name'] = $this->db->get('gambarProduk')->result()[0]->maks;
    $extension = pathinfo($_FILES["gambarProduk"]['name'], PATHINFO_EXTENSION);
    $fullpath = $config['upload_path'].$config['file_name'].'.'.$extension;

    if(file_exists($fullpath)){
        unlink($fullpath);
    }
    $this->db->where('idGambar',$config['file_name']);
    $this->db->update('gambarProduk',array('extension'=>$extension));
    $this->load->library('upload',$config);
    if(!$this->upload->do_upload('gambarProduk')){
        $this->session->set_flashdata('uploadGambarProduk',2);
    }
}
Hafid
  • 1
  • 1
  • If your `id` column is auto_increment, you can use the value of [`LAST_INSERT_ID`](https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id) (use `$insert_id = $this->db->insert_id();` after your `INSERT` query). That is guaranteed to be unique to the process which does the `INSERT`. – Nick Dec 22 '18 at 07:07
  • use server time in milliseconds to name your image.did you try it? – Optimaz Prime Dec 22 '18 at 07:08
  • thanks for both of you OptimazID, and Nick, apreciate it, and that's useful answer – Hafid Dec 22 '18 at 07:27

1 Answers1

0

Use server time and add some random number to that time to avoid problems when uploading multiple images.

$imgName = $_FILES["images"]["name"];
$imgTempName = $_FILES["images"]["tmp_name"];
$target_dir = "images/";    
$target_file = $target_dir . basename($imgName);
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
//file name uses server time + add random number
$fileName = $target_dir . round(microtime(true) * 10000) . rand() . "." .$imageFileType;

$source_img = $imgTempName;
$destination_img = $fileName;
Optimaz Prime
  • 857
  • 10
  • 11
  • Thanks, apreciate it, and it can one of lot answer, and still want to hear the other, and i think yours better than mine, and i will use it.... again, thanks bro.... – Hafid Dec 22 '18 at 07:39