微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – file_get_contents与相对路径

我有以下目录结构.
/var/www/base/controller/detail.PHP
/var/www/base/validate/edit.json
/var/www/html

在/var/www/base/controller/detail.PHP中,如何使用相对路径的file_get_contents()读取/var/www/base/validate/edit.json?我尝试过以下操作:

//Failed to open stream: No such file or directory (error no: 2)
$json=file_get_contents('detail.PHP');

//No error,but I don't want this file and was just testing
$json=file_get_contents('detail.PHP',FILE_USE_INCLUDE_PATH);

//Failed to open stream: No such file or directory (error no: 2)
$json=file_get_contents('./validate/edit.json',FILE_USE_INCLUDE_PATH);
//Failed to open stream: No such file or directory (error no: 2)
$json=file_get_contents('../validate/edit.json',FILE_USE_INCLUDE_PATH);
//Failed to open stream: No such file or directory (error no: 2)
$json=file_get_contents('././validate/edit.json',FILE_USE_INCLUDE_PATH);
//Failed to open stream: No such file or directory (error no: 2)
$json=file_get_contents('../../validate/edit.json',FILE_USE_INCLUDE_PATH);

//This works,but I want to use a relative path
$json=file_get_contents(dirname(dirname(__FILE__)).'/validate/edit.json');
你有没有尝试过:
$json = file_get_contents(__DIR__ . '/../validate/edit.json');

__DIR__一个有用的魔术常数.

为什么,见http://yagudaev.com/posts/resolving-php-relative-path-problem/

When a PHP file includes another PHP file which itself includes yet another file — all being in separate directories — using relative paths to include them may raise a problem. PHP will often report that it is unable to find the third file,but why? Well the answer lies in the fact that when including files in PHP the interpreter tries to find the file in the current working directory. In other words,if you run the script in a directory called A and you include a script that is found in directory B,then the relative path will be resolved relative to A when executing a script found in directory B. So,if the script inside directory B includes another file that is in a different directory,the path will still be calculated relative to A not relative to B as you might expect.

原文地址:https://www.jb51.cc/php/132459.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐