0

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.

fpolloa
  • 99
  • 4
  • 13

2 Answers2

1

When working with files you will want to use PATHS not URLS.
So
$file = "http://example.com/Song.txt"; becomes
$file = "/the/path/to/Song.txt";

Next:

$file1 = '/absolute/path/to/my/first/file.txt';
$file2 = '/absolute/path/to/my/second/file.txt';
$fileContents1 = file_get_contents($file1);
$fileContents2 = file_get_contents($file2);
if (md5($fileContents1) != md5($fileContents2)) {
    // put the contents of file1 in the file2
    file_put_contents($file2, $fileContents1);
}

Also, you should check that your files are writable by the webserver, that is 0666 permission.

Twisted1919
  • 2,430
  • 1
  • 19
  • 30
1

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);
Tasos Bitsios
  • 2,699
  • 1
  • 16
  • 22