PHP create file with specific name [closed]

Even though as pointed out in comments your question is unclear, I think I understand what you want to do, though as stated, you should edit the question to make it more clear.

If I’m right, what you’re asking is how to create new files with a numerical suffix one higher than the previous file to prevent overwrites. A simple way to do this is a for() loop that checks if the core file name + count number already exists, and keep going until you find one that doesn’t exist already. Then you can store the filename with the iteration of the loop where the file doesn’t exist, and finally write to a new file with that name. As an example;

<?php
    /* Here you can set the core filename (from your question, "LMS"),
    as well as the number of maximum files. */
    $coreFileName   = "LMS";
    $maxFilesNum    = 100;

    // Will store the filename for fopen()
    $filename = "";

    for($i = 0; $i < $maxFilesNum; $i++)
    {
        // File name structure, taken from question context
        $checkFileName = $coreFileName . "-" . str_pad($i, 3, 0, STR_PAD_LEFT) . ".txt";

        // If the file does not exist, store it in $filename for writing
        if(!file_exists($checkFileName))
        {
            $filename = $checkFileName;
            break;
        }
    }

    $fd = fopen($filename, "w");
    fwrite($fd, "Jane Doe"); // Change string literal to the name to write to file from either input or string literal
    fclose($fd); // Free the file descriptor

I’ve tested it and it works, so every time the page is refreshed a new file is created with the numerical suffix one higher than the previously created file. I’ve made this so it will only create up to a 100 files max, you can adjust this how you please with the $maxFilesNum variable near the top, however I do recommend setting a limit so that your file-system on your local or remote server doesn’t get flooded with files.

Edit: Now includes padding for 001, 002 … 100

Leave a Comment