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.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c