RAN RAN
RAN RAN

Reputation: 33

how to add number in picture when upload if same file name of picture

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 ^^

Upvotes: 1

Views: 2670

Answers (5)

Krish R
Krish R

Reputation: 22711

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))
{


}

Upvotes: 0

Veerendra
Veerendra

Reputation: 2622

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

Upvotes: 1

Glavić
Glavić

Reputation: 43552

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:

Upvotes: 1

Harish Singh
Harish Singh

Reputation: 3329

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;

Upvotes: 0

Fyntasia
Fyntasia

Reputation: 1143

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)

Upvotes: 1

Related Questions