Lorenz
Lorenz

Reputation: 51

PHP script to create file if no exist

I have a small problem with my php code. Please take a look:

<?php
$urlud = $json['url'];
$content = 'Content 1 if file no exist will generate';
$filename = $json['id'].".html";
if (file_exists($filename)) {
    echo "File exists!";
} else {
    file_put_contents('dir1/'. $filename, $content, FILE_APPEND | LOCK_EX);
}
?>
<?php
$urlud = $json['url'];
$content = 'Content 2 if file no exist will generate';
$filename = $json['id'].".html";
if (file_exists($filename)) {
    echo "File exists!";
} else {
    file_put_contents('dir2/'. $filename, $content, FILE_APPEND | LOCK_EX);
}
?>

This code will generate 2 files in different directories with different content. My problem is:

  1. This code keeps replacing my old file content. Any solution to make it create only if the file doesn't exist ?
  2. Any other input to make this code simpler?

Thanks.

Upvotes: 2

Views: 4680

Answers (1)

Harald Doderer
Harald Doderer

Reputation: 108

if (file_exists('dir1/'. $filename))

and

if (file_exists('dir2/'. $filename))

You have to check the full path of the file not only the file name. E.g. imagine $filename to be "readme.txt" This file is probably not existing in your script path. And you expect it to be in dir1 or dir2.

Upvotes: 2

Related Questions