Search code examples
phpuploadrenamefilenamesauto-increment

auto increment number within filename


My users can upload profile pictures, one by one, but as often as they want.

Let's assume user 1 uploads an image, this code will store it to my uploads-folder:

<?php

$fileData = pathinfo(basename($_FILES["fileToUpload"]["name"]));

$fileName = 'user_id_#1#_profilepic_#' . uniqid() . '#.' . $fileData['extension'];

$target_path = "uploads/" . $fileName;

while(file_exists($target_path)) {
    $fileName = 'user_id_#1#_profilepic_#' . uniqid() . '#.' . $fileData['extension'];
    $target_path = ($_SERVER['DOCUMENT_ROOT'] . "uploads/" . $fileName);
}

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_path)) {

    echo "The image was successfully uploaded. <a href='index.php'>Add another image</a>";
}
else {
    echo "There was an error uploading the file, please try again!";
}

?>

This uniqid() needs to be replaced, because it's a nightmare to find the images later on in the right order.

I want the images - after uploading - to look like this:

user_id_#1#_profilepic_#1#.jpg
user_id_#1#_profilepic_#2#.jpg
user_id_#1#_profilepic_#3#.png
user_id_#1#_profilepic_#4#.gif
user_id_#1#_profilepic_#5#.jpg
and so on...

How can I do this? I don't have any ideas so far.


Solution

  • You can increment by file number in your directory (not recommended if your user can delete his pictures) :

    $total_files = count(glob("./*",GLOB_BRACE)); // count files in directory
    echo $total_files;
    

    OR :

    use a text file where you record a number.

    For exemple : You user upload a file : Get the current number in the text file -> add +1 and rename the file with this number -> record the new number in the txt file.

    The best way should be a unique ID from database record but you maybe not use a DB.

    I hope that help you.

    Have a nice day !