user3352340
user3352340

Reputation: 145

Check if filename exists and

I wondered if there were a way to check if the filename exists and then to add a number after it, I know this - in a basic for is possible so if someone does it once it'll add 1 after it.

But how would you get it to check if someone has done it more than once? So the first time it would add a 1 then a 2 then a 3 and so on?

$title = $_POST['title'];
$content = $_POST['content'];
$compile = $title. "\r\n" .$content;
$content = $compile;
$path = "../data/" .md5($title). ".txt";
$fp = fopen($path,"wb");
fwrite($fp,$content);
fclose($fp);

$con=new mysqli("###","###_public","###","###"); 
if (!($stmt = $con->prepare("INSERT INTO `blog_posts` (`post_title`,`post_content`,`post_date`) VALUES (?,?,?)")) || !is_object($stmt)) {
    die( "Error preparing: (" .$con->errno . ") " . $con->error);
}
$stmt->bind_param('sss', $_POST['title'], $path, $_POST['date']);
if($stmt->execute()) { 
    echo "Successfully Posted";
} else {
    echo "Unsuccessfully Posted";
}
    $stmt->close();

Thanks for any help in advance

Upvotes: 1

Views: 465

Answers (3)

Tularis
Tularis

Reputation: 1506

You can use something like this:

<?php
if(file_exists($filename)) { // check if the file exists in the first place
   $i = 1;
   while(file_exists($filename.$i)) { // check if the filename with the index exists. If so, increase the $i by 1 and try again
      $i++;
   }
   rename($filename, $filename.$i); // rename the actual file
} else {
   // file did not exist in the first place
}

Upvotes: 1

blue
blue

Reputation: 1949

  1. Do not add strings at the end of file name - you would eventually hit the OS file name length limit pretty soon. You would also fail to recognize the last added number, when the string gets too big - you'd have to parse all the numbers from the beginning.
  2. Use glob() to search for a file name.
  3. Parse the file names found for the number at the end and increment that number.
  4. Use rename() on the file name and check the return status to avoid racing conditions.
  5. Generally avoid that - use a database or any other system that supports atomic operations.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

The general idea would be like this:

$basefilename = "somefile";
$filename = $basefilename;
$i = 0;
while(file_exists("../data/".$filename.".txt") $filename = $basefilename.(++$i);

Adapt as needed.

Upvotes: 1

Related Questions