1

I have this code for upload

$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);

move_uploaded_file($_FILES["image"]["tmp_name"],"photo/" . $_FILES["image"]["name"]);

$location="photo/" . $_FILES["image"]["name"];

then the insert $location code for sql to add

The Question is how to have my picture file name number add ex: if i have "Picture.jpg "uploaded if i will upload again and same file name the output of the filename will be Picture(1).jpg and if I upload again with the same file name the output filename will be Picture(2).jpg and so on I want the "()" to increment if ever i will upload same file name. thanks in advance ^^

Krish R
  • 22,583
  • 7
  • 50
  • 59
RAN RAN
  • 33
  • 1
  • 6

5 Answers5

1

This code is untested, but I would think something along the lines of:

if (file_exists('path/to/file/image.jpg')){
 $i = 1;
 while (file_exists('path/to/file/image ('.$i.').jpg')){
   $i++;
 }
 $name = 'image ('.$i.');
}

And then save the image to $name. (which at some point will result in image (2).jpg)

Fyntasia
  • 1,133
  • 6
  • 19
  • Wow answer. I was thinking to go for recursive function and what not, this is simple logic. 10 years old answer does the trick for me :). – Neo Jun 14 '23 at 05:06
1

This can be achived with loop:

$info = pathinfo($_FILES['image']['name']);
$i = 0;
do {
    $image_name = $info['filename'] . ($i ? "_($i)" : "") . "." . $info['extension'];
    $i++;
    $path = "photo/" . $image_name;
} while(file_exists($path));

move_uploaded_file($_FILES['image']['tmp_name'], $path);

You should also sanitize input file name:

Community
  • 1
  • 1
Glavić
  • 42,781
  • 13
  • 77
  • 107
1

If you want to have a unique image name after upload even if they have same name or they are uploading in loop means multiple upload.

$time = time() + sprintf("%06d",(microtime(true) - floor(microtime(true))) * 1000000);

$new_name=$image_name.'_'.$time.'.'.$extension 

You can add the image name with a unique time stamp which differ each nano seconds and generate unique time stamp

Veerendra
  • 2,562
  • 2
  • 22
  • 39
0

try this

$path = "photo/" . $_FILES["image"]["name"];
$ext = pathinfo ($path, PATHINFO_EXTENSION );
$name = pathinfo ( $path, PATHINFO_FILENAME ] );

for($i = 0; file_exists($path); $i++){
if($i > 0){
  $path =  "photo/" .$name.'('.$id.').'.$ext;
} 
}

echo $path;
Harish Singh
  • 3,359
  • 5
  • 24
  • 39
0

Can you try this,

$name = $_FILES['image']['name'];
$pathinfo = pathinfo($name);
$FileName = $pathinfo['filename'];
$ext = $pathinfo['extension'];
$actual_image_name = $FileName.time().".".$ext; 
 $location="photo/".$converted_name;    
if(move_uploaded_file($tmp, $location))
{


}
Krish R
  • 22,583
  • 7
  • 50
  • 59