Search code examples
phpfile-uploadfilenamesfile-renamefile-exists

Rename a file if same already exists


I'm trying to upload a file and rename it if it already exists. The way I want i to do is that when det same file uploads the name just adds 1, then 2, then 3, and so on.

Example: If file "file" exists, the new file should be "file1", then the next one "file2".

I've seen some examples on the net, but nothing that I could see fit to my code (noob)

This is my code now:

$id = $_SESSION['id'];
$fname = $_FILES['dok']['name'];
if ($_FILES['dok']['name'] !=""){
// Checking filetype
if($_FILES['dok']['type']!="application/pdf")     {die("You can only upload PDF files");}

// Checking filesize
if ($_FILES['dok']['size']>1048576) {die("The file is too big. Max size is 1MB");}

// Check if user have his own catalogue
if (file_exists("filer/".$id."/")) {
// Moving the file to users catalogue
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);}

//If user don't have his own catalogue 
else {
// Creates new catalogue then move the file in place
mkdir("filer/".$id);
move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);   } }

Can somebody help me where I can put in code that solves this problem? Big thank you!


Solution

  • $id = $_SESSION['id'];
    $fname = $_FILES['dok']['name'];
    if ($_FILES['dok']['name'] !=""){
        // Checking filetype
        if($_FILES['dok']['type']!="application/pdf") {
            die("You can only upload PDF files");
        }
        // Checking filesize
        if ($_FILES['dok']['size']>1048576) {
            die("The file is too big. Max size is 1MB");
        }
    
        if(!is_dir("filer/".$id."/")) {
            mkdir("filer/".$id); 
        }
    
        $rawBaseName = pathinfo($fname, PATHINFO_FILENAME );
        $extension = pathinfo($fname, PATHINFO_EXTENSION );
        $counter = 0;
        while(file_exists("filer/".$id."/".$fname)) {
            $fname = $rawBaseName . $counter . '.' . $extension;
            $counter++;
        };
    
        move_uploaded_file($_FILES['dok']['tmp_name'],"filer/".$id."/".$fname);  
    
    } 
    

    But don't forget to secure your script (eg see comment of Marc B above) and maybe you could optimize some more ;-)