Create unique id for uploaded image

3.5k views Asked by At

How to create unique id for uploaded file using this code.

Code uploads the image, but when you upload it using iPhone all images are come as image.jpg. So I need a function to rename existing file or just to create unique id for each.

<form enctype="multipart/form-data" action="" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form>
<?php 
function findexts ($filename)  {  $filename = strtolower($filename) ;  $exts = split("[/\\.]", $filename) ;  $n = count($exts)-1;  $exts = $exts[$n];  return $exts;  }   

$ext = findexts ($_FILES['uploaded']['name']) ; 


$ran = rand () ; 
$ran2 = $ran.".";  
$target = "uploads/";

if(file_exists("uploads/$filename")) unlink("uploads/$filename");move_uploaded_file($target, "uploads/$filename");

if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))  { echo "The file has been uploaded as ".$ran2.$ext; }  else { echo "Sorry, there was a problem uploading your file."; } 
$target = $target . $ran2.$ext;
1

There are 1 answers

1
hakki On

You can use uniqid() function for unique image names. It gets two parameters. First: prefix, Second: more entropy.

See details here: http://php.net/manual/en/function.uniqid.php

 <form enctype="multipart/form-data" action="" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form>
    <?php 
    function findexts ($filename)  {  
       $filename = strtolower($filename) ;  
       $exts = split("[/\\.]", $filename) ;  
       $n = count($exts)-1;  
       $exts = $exts[$n];  return $exts;  
    }   

    $ext = findexts ($_FILES['uploaded']['name']) ; 

    //unique image
    $new_image_name = uniqid("IMG_",false);
    $final_name = $new_image_name.".".$ext;

    //Target directory
    $target = "uploads/";

    if(file_exists("uploads/$final_name")) unlink("uploads/$final_name");move_uploaded_file($target,"uploads/$final_name");

    if(move_uploaded_file($_FILES['uploaded']['tmp_name'], $target))  { echo "The file has been uploaded as ".$final_name; }  else { echo "Sorry, there was a problem uploading your file."; } 
    $target = $target . $final_name;