Search code examples
phpfopen

fopen doesn´t work with something different than r php


I have a problem with the fopen function and the opening mode argument.

Code

function writeOnFile($url, $text)
{
    $fp = fopen($url, "r");
    echo "<br>read: ".fgets($fp);
    //fwrite($fp, $text);
    fclose($fp);
}

If I use "r" as the opening mode the echo line works... but if I change this argument for any other (using the same url file) it stops working and only see "read:" and nothing else. I tried with "w+" "r+" "a+"... but no one works.
What I am trying to read is a txt file and I changed the permissions of the file and now are 777...

What am I doing wrong?


Solution

  • Given your variable naming, $url suggests you're trying to write to a http://example.com/.... This is not possible. You cannot "write" to a url, because PHP has absolutely NO idea what protocol the remote server is expecting. E.g. PHP by some miracle decides to let this URL through, and uses http POST... but the server is expecting an http PUT. Ooops, that won't work.

    As well, never EVER assume an operation on an external resource succeeded. Always assume failure, and treat success as a pleasant surprise:

    function writeOnFile($url, $text)
       if (!is_writeable($url)) {
          die("$url is not writeable");
       }
       $fp = fopen($url, "w");
       if (!$fp) {
          die("Unable to open $url for writing");
       }
       etc...
    }