Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I've got a PHP Script that creates a txt file using a form and saves it under the filename "businesscard-1.txt". If i gonna run the Script again it overrides the "businesscard-1.txt" with the new data. But i want it to create a new file with the name "businesscard-2.txt" and if this exists too, than it should get the name "businesscard-3.txt" etc. Does anyone know how to do that ?

<?php

$part1 = $_POST["Imputfield-1"];
$part2 = $_POST["Imputfield-2"];
$part3 = $_POST["Imputfield-3"];

$file = fopen('businesscard-1.txt', 'w+');

ftruncate($file, 0);

$content =
$part1. PHP_EOL .
$part2. PHP_EOL .
$part3. PHP_EOL ;

fwrite($file , $content);
fclose($file );

header("Location: Page2.htm");
die();

?> 
share|improve this question
    
If you need help with specific code, please ask on Stack overflow. Here is a description of the types of questions that are welcome on Programmers. – Jay Elston yesterday

You could:


use tempnam to create a file with a unique filename:

$tmpfname = tempnam('/mydir', 'businesscard-');
$file = fopen($tmpfname, 'w+');

pro

  • this is very simple

con


generate a unique ID to be appended to the filename:

$filename = uniqid('businesscard-');
$file = fopen($filename, 'w+');

The identifier is based on the current time in microseconds (the return value is little different from microtime. Further details here).

pros

  • simple
  • recording order can be inferred from filename

con

  • pay attention to concurrent requests for ID generation

adopt a file_exists based approach:

$i = 0;

while (!$filename)
{
  if (!file_exists("businesscard-$i.txt"))
    $filename = "businesscard-$i.txt";

  $i++;
}

pro

  • this is what you was thinking of

cons

  • race conditions
  • performance

Store somewhere the last used ID (database / file), e.g.

function get_next()
{
  $num = (int)file_get_contents('generator.txt');
  $num += 1;
  file_put_contents('generator.txt', $num);

  return $num;
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.