2

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.

4
  • simple, add counter with file name Commented Jul 18, 2015 at 3:34
  • maybe since you are writing to dir2 you ahould also be checking for the file there Commented Jul 18, 2015 at 3:45
  • another solution, use php randon string function and add it with file name so you will have $filename $string and $string will be unique everytime Commented Jul 18, 2015 at 3:52
  • i'm still unable to do that.. already change dir2 function to different call like $filename2 and still have same problem.. Commented Jul 18, 2015 at 3:55

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

1 Comment

hi @Harald Doderer, thanks for your solution.. this work like i want.. old file keep on there and not replacing with new one..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.