带有相对路径的file_get_contents [英] file_get_contents with relative path

查看:118
本文介绍了带有相对路径的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?我尝试了以下方法:

Within /var/www/base/controller/detail.php, how do I use file_get_contents() with a relative path to read /var/www/base/validate/edit.json? I've tried the following:

//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__ 是一个有用的魔术常数.

__DIR__ is a useful magic constant.

出于某些原因,请参见 http://yagudaev.com/posts/解决php-relative-path-problem/.

For reasons why, see http://yagudaev.com/posts/resolving-php-relative-path-problem/.

当一个PHP文件包含另一个PHP文件时,该文件本身又包含另一个文件(都位于单独的目录中),使用相对路径包含它们可能会引起问题.

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通常会报告它找不到第三个文件,但是为什么呢? 答案很好,那就是当在PHP中包含文件时,解释器会尝试在当前工作目录中查找文件.

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.

换句话说,如果您在名为A的目录中运行脚本,并且包含在目录B中找到的脚本,那么当执行在目录B中找到的脚本时,相对路径将相对于A解析.

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.

因此,如果目录B中的脚本包含另一个目录中的另一个文件,则路径仍将相对于A计算,而不是您所期望的相对于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.

这篇关于带有相对路径的file_get_contents的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆