How to autoincrement a filename created with a PHP page

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jej1216
    New Member
    • Aug 2006
    • 40

    How to autoincrement a filename created with a PHP page

    I have a process in a PHP page that creates a file, and it works fine:
    Code:
    if ("$_REQUEST[severity]" == "Level1-No_Obvious_Harm") {
         $sevvar = "1";
    } elseif ("$_REQUEST[severity]" == "Level2-Non-permanent_Harm") {
         $sevvar = "2";
    } elseif ("$_REQUEST[severity]" == "Level3-Semi-permanent_Harm") {
         $sevvar = "3";
    } elseif ("$_REQUEST[severity]" == "Level4-Major_Permanent_Harm") {
         $sevvar = "4";
    } elseif ("$_REQUEST[severity]" == "Level5-Death") {
         $sevvar = "5";
    } else {
         $sevvar = "Nada";
    }
    
      $file = "notify/$sevvar".".$_REQUEST[fac_id]".".txt";
      $handle = fopen($file, 'w');
      fclose($handle);
    The name is based on a severity level data value and hospital name.

    I now need to increment the filename since it is possible to need more than one file with the same severity level and hospital.

    I see where autoincrementin g a database field is covered in PHP, but what about autoincrementin g a filename that is created by PHP?

    TIA,

    jej1216
  • coolsti
    Contributor
    • Mar 2008
    • 310

    #2
    I don't think you can autoincrement the filename using just PHP.

    One way to do it would be to do a directory search of all filenames that match your basic name without the incremental number, extract the incremental number part and find out the largest value. Then create a filename by incrementing the largest value by 1.

    What I do not know about here is how to avoid concurrency issues with multiple users. If for example two persons run the same script at the same time, both scripts may locate the same "largest value" and attempt to create the same "next value" filename. You would need some kind of lock on this or at least a bail-out-and-try-again scheme when coming to the line that actually performs the file creation (by first looking if the target file still does not exist).

    Maybe someone else can answer the concurrency issue here.

    Comment

    • Atli
      Recognized Expert Expert
      • Nov 2006
      • 5062

      #3
      Hi.

      Personally I would just add the current timestamp plus a string of a random number, like say 100-999.
      That would make a pretty unique number that you could add to you filename.

      Or you could try adding the total number of existing files to your new filename. This may be a little slower than the other method, seeing as it has to do extra file-system operations, but may look slightly better.

      Both have a slight chance of causing a collision, but that would be rare and easily manageable.

      Comment

      Working...