Search code examples
phphtmlformsuniquefopen

php create new .txt file with specific name ending


I have a site which has an HTML form that forwards some information to php code. Then once the php document has gotten the code it creates a new document newDocu.txt and then it writes two values to it. Only problem is that when this has been done one time, it will just append to that same document as it has already been created.

I was then wondering if there is a way to change the naming of the new document, so lets say it would look at the current documents in the folder and then lets say there are no documents, then it would be newDocu1.txt or if there were three documents, then the new txt file would be called newDocu4.txt. To make sure it doesn't just write the new info to a current document.

Any help is very much appreciated.

Here is my current php file

<?php

    $field_fname = $_POST['fnameInput'];
    $field_email = $_POST['emailInput'];

    $filename = "../public_html/NO/newDocu.txt";

    $f_data= '
    First Name : '.$field_fname.'
    Email : '.$field_email.'
    --------------------------------------------------
    ';

    echo 'Thank you!';

    $file = fopen($filename, "a");
    fwrite($file,$f_data);
    fclose($file);

    echo '<meta HTTP-EQUIV="REFRESH" content="0; url=index.html">';

?>

Solution

  • Add this code just after your $filename variable:

    $mainname= $filename;
    $version = 1;
    while(file_exists($filename))
    {
        $filename = str_replace('.txt', $version . '.txt', $mainname);
        $version++;
    }