我有以下目录结构.
/var/www/base/controller/detail.php
/var/www/base/validate/edit.json
/var/www/html
Run Code Online (Sandbox Code Playgroud)
在内部/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');
Run Code Online (Sandbox Code Playgroud)
Sam*_*son 68
你有没有尝试过:
$json = file_get_contents(__DIR__ . '/../validate/edit.json');
Run Code Online (Sandbox Code Playgroud)
__DIR__ 是一个有用的魔术常数.
有何原因,请参阅http://yagudaev.com/posts/resolving-php-relative-path-problem/.
当PHP文件包含另一个PHP文件时,该文件本身包含另一个文件 - 所有文件都在不同的目录中 - 使用相对路径来包含它们可能会引发问题.
PHP会经常报告它无法找到第三个文件,但为什么呢?答案在于,当在PHP中包含文件时,解释器会尝试在当前工作目录中查找该文件.
换句话说,如果在名为A的目录中运行脚本并且包含在目录B中找到的脚本,则在执行目录B中找到的脚本时,将相对于A解析相对路径.
因此,如果目录B中的脚本包含位于不同目录中的另一个文件,则仍将相对于A计算路径,而不是相对于B,如您所料.
小智 7
尝试使用这个
$json = file_get_contents("/path/to/your/file/edit.json", true);
Run Code Online (Sandbox Code Playgroud)
从 PHP 5 开始,FILE_USE_INCLUDE_PATH 常量可用于触发包含路径搜索。如果启用严格类型,这是不可能的,因为 FILE_USE_INCLUDE_PATH 是一个 int。请改用 TRUE。
| 归档时间: |
|
| 查看次数: |
41973 次 |
| 最近记录: |