Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

php - file_get_contents with relative path

I have the following directory structure.

/var/www/base/controller/detail.php
/var/www/base/validate/edit.json
/var/www/html

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');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried:

$json = file_get_contents(__DIR__ . '/../validate/edit.json');

__DIR__ is a useful magic constant.

For reasons why, see 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...