PHP 警告:无法打开流:没有这样的文件或目录,文件路径错误

PHP Warning: failed to open stream: No such file or directory, File Path Errors

我无法理解 PHP 如何选择编译或如何在文件中包含文件。

这是我的文件结构:

我需要 secrets.phphead.php 内。 我需要 head.php 里面 index.php.

head.php

require "../environment/secrets.php";

index.php

require "php/head.php";

我收到一个错误:

Warning: require_once(../environment/secrets.php): failed to open stream: No such file or directory in /home/ubuntu/workspace/Cally Dai/php/head.php on line 2 Call Stack: 0.0002 234760 1. {main}() /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2. require_once('/home/ubuntu/workspace/Cally Dai/php/head.php') /home/ubuntu/workspace/Cally Dai/index.php:5 Fatal error: require_once(): Failed opening required '../environment/secrets.php' (include_path='.:/usr/share/php:/usr/share/pear') in /home/ubuntu/workspace/Cally Dai/php/head.php on line 2 Call Stack: 0.0002 234760 1. {main}() /home/ubuntu/workspace/Cally Dai/index.php:0 0.0007 236632 2. require_once('/home/ubuntu/workspace/Cally Dai/php/head.php') /home/ubuntu/workspace/Cally Dai/index.php:5

我哪里错了?

按照我的感觉,路径肯定是从ubuntu中的root开始的。试试你的代码,
require_once("/home/ubuntu/workspace/Cally Dai/php/head.php")

当一个 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. 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. This is a very important point to understand about the difference between PHP and other languages like C/C++.

一种解决方案是使用 dirname(__FILE__):

Use dirname(__FILE__) – The __FILE__ constant contains the full path and filename of the script that it is used in. The function dirname() removes the file name from the path, giving us the absolute path of the directory the file is in regardless of which script included it. Using this gives us the option of using relative paths just as we would with any other language, like C/C++. We would prefix all our relative path like this:

include(dirname(__FILE__) . "/dir/script_name.php");

来源:http://yagudaev.com/posts/resolving-php-relative-path-problem/