Search code examples
phptext-filesserver-sidefwrite

PHP - Write text file content in another text file


I want to check if the content of a text file is the same as another, and if it isn't, write one into the other. My code is as follows:

<?php $file = "http://example.com/Song.txt";
$f = fopen($file, "r+");
$line = fgets($f, 1000);
$file1 = "http://example.com/Song1.txt";
$f1 = fopen($file1, "r+");
$line1 = fgets($f1, 1000);
if (!($line == $line1)) {
    fwrite($f1,$line);
    $line1 = $line;
    };
print htmlentities($line1);
?>

The line is being printed out, but the content isn't being written in the file.

Any suggestions about what might be the problem?

BTW: Im using 000webhost. I'm thinking it's the web hosting service but I've checked and there shouldn't be a problem. I've also checked the fwrite function here: http://php.net/manual/es/function.fwrite.php. Please, any help will be very aprecciated.


Solution

  • What you're doing will only work for files up to 1000 bytes. Also - you're opening the second file, which you want to write to, using "http://", which means that fopen internally will use an HTTP URL wrapper. These are read-only by default. You should fopen the second file using its local path. Or, to make this simpler, you can do this:

    $file1 = file_get_contents("/path/to/file1");
    $path2 = "/path/to/file2";
    $file2 = file_get_contents($path2);
    if ($file1 !== $file2)
        file_put_contents($path2, $file1);