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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.