Kubloy Kubloy - 1 month ago 16
PHP Question

fwrite if string doesn't exist in file

I am currently working an auto-content-generator script's sitemap. I got to know that google accept sitemap in simple text file that contains one URL per line.

so I created a file named

1.txt
and wrote a script to add current page url to
1.txt
when a user visits.

test.php
is,

$file = 'assets/sitemap/1.txt';
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";
$file = fopen($file, 'a');
fwrite($file, $url);
fclose( $file );


This script writes the page url to 1.txt every time someone hits the page. But the problem is, it creates too much duplicate links. So I want to add a filter to not add a string (url in this case) if it already exists.

After surfing a while, I got a solution here (second snippet) that is resource friendly,

http://stackoverflow.com/a/9059047/6425611

I made the following modification but it is not working (not adding anything at all).

$file = 'assets/sitemap/1.txt';
$url = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";
if(exec('grep '.escapeshellarg($url).' assets/sitemap/1.txt')) {}
else{
$file = fopen($file, 'a');
fwrite($file, $url);
fclose( $file );
}

Answer

This is hopefully easier to understand:

$file = 'assets/sitemap/1.txt';
$url  = "http://".$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]."\n";

$text = file_get_contents($file);

if(strpos($text, $url) === false) {
    file_put_contents($file, $url, FILE_APPEND);
}
  • Read the file contents into a string $text using file_get_contents()
  • Check if $url is in the string $text using strpos()
  • If $url is not in the string $text, append the $url to the file using file_put_contents()
  • edit: extra } after false) { removed.