doupoji3856 2013-04-10 22:30 采纳率: 100%
浏览 64
已采纳

PHP如何解释本地路径以及它在何处打开文件?

I'm trying to figure out how a WordPress theme works. For this, I want to write to a file from various functions. The file is at the root of the site.

fwrite(fopen("output.txt", "a"), "Test output
");

From /test.php, this outputs to /output.txt. I'd like to write the value of a variable in a deeply-nested function. Copy/pasting the above code outputs to somewhere I can't find. This:

fwrite(fopen("/output.txt", "a"), "Test output
");

doesn't work, either. It raises:

Warning: fopen(/output.txt) [function.fopen]: failed to open stream: Permission denied in /public_html/test.php on line 17

Warning: fwrite() expects parameter 1 to be resource, boolean given in /public_html/test.php on line 17

The manual specifies some stuff about schemes and wrappers, but doesn't say very much about paths.

If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled safe mode, or open_basedir, further restrictions may apply.

How do I properly reference the path I want, and how does PHP choose where to write with a relative path?

  • 写回答

1条回答 默认 最新

  • dongtang1944 2013-04-10 22:33
    关注

    If you are not using absolute paths, the path is relative to the index.php of wordpress. To access a file that is stored in the same folder as your php file use the global constant __DIR__:

    fwrite(fopen(__DIR__ ."/output.txt", "a"), "Test output
    ");
    

    __DIR__ will give you the absolute path to the current php script.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改