fopen doesn´t work with something different than r php

若如初见. 提交于 2019-12-13 22:12:43

问题


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?


回答1:


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...
}


来源:https://stackoverflow.com/questions/26845814/fopen-doesn%c2%b4t-work-with-something-different-than-r-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!