Jump to content

Writing to and Reading from a File


sjnagy

Recommended Posts

This works on my local host, but when I upload it to the server... I get the 'Unable to open file!' error. Why does it work on localhost, but not on the server. I have tried commenting it out, but all code after this won't run. 

 

Please let me know if you can offer any help 

 

*************************************************************************************************************************

<?php

$streets = fopen("files/streets.txt", "w") or die("Unable to open file!");

$txt = "Congress\n";

fwrite($streets, $txt);

$txt = "Sixth Street\n";

fwrite($streets, $txt);

$txt = "Second Street\n";

fwrite($streets, $txt);

fclose($streets);

?>

<?php

$streetdescription = fopen("files/streetdescription.txt", "w") or die("Unable to open file!");

$txt = "– Main north and south city thoroughfare\n";

fwrite($streetdescription, $txt);

$txt = "– Active bar scene.\n";

fwrite($streetdescription, $txt);

$txt = "– Active restaurant and café scene";

fwrite($streetdescription, $txt);

fclose($streetdescription);

?>

<?php

$myfile = fopen("files/streets.txt", "r") or die("Unable to open file!");

$myfile2 = fopen("files/streetdescription.txt", "r") or die("Unable to open file!");

// Output one line until end-of-file

while(!feof($myfile)) {

  echo fgets($myfile) ;

  echo fgets($myfile2) . "<br>";

}

fclose($myfile);

?>

 

Link to comment
Share on other sites

And don't use relative paths. It only leads to more confusion.

 

If you want to reference a file relative to the current script, use the __DIR__ constant which contains the absolute path to the script.

$streets_path = __DIR__.'/files/streets.txt';    // this will be resolved to /path/to/script/files/streets.txt
Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.