PHP CLI include()找不到该文件

时间:2021-11-16 15:06:39

Structure of my files is like so:

我的文件结构是这样的:

config.php
script
|--myscript.php

myscript.php

myscript.php

<?php
require '../config.php';
?>

When executing php /path/to/myscript.php I get Warning: require(../config.php): failed to open stream: No such file or directory.

执行php /path/to/myscript.php时,我收到警告:require(../ config.php):无法打开流:没有这样的文件或目录。

Whats the reason?

什么原因?

5 个解决方案

#1


24  

That's because your current working directory is the one you call your command at, not the one your script is located in.

那是因为您当前的工作目录是您调用命令的目录,而不是脚本所在的目录。

Use

使用

require __DIR__ . '/../config.php';

instead. __DIR__ is a const that points to the directory current file is located in.

代替。 __DIR__是一个指向当前文件所在目录的const。

#2


6  

One way I do it, is like this:

我这样做的一种方式是这样的:

php -d include_path=/path/to/config.php script.php

-d is used to set INI directives at runtime, so you don't have any changing code/configs/directories.

-d用于在运行时设置INI指令,因此您没有任何更改的代码/配置/目录。

#3


2  

If you don't want to (or can't) change the require line in your code, just cd to the directory that your script expects to be executed within before running your script:

如果您不想(或不能)更改代码中的require行,只需在运行脚本之前cd到脚本期望执行的目录:

cd /path/to
php /path/to/myscript.php

#4


1  

Most likely you got wrong working directory so your relative paths is not pointing where you expect it to. To see how PHP sees it add:

很可能你的工作目录错了,所以你的相对路径没有指向你期望的位置。要了解PHP如何看待它添加:

echo getcwd();

as the 1st line of your script.

作为脚本的第一行。

#5


0  

You need to use absolute path or change working directory:

您需要使用绝对路径或更改工作目录:

chdir(dirname(__FILE__));

CHDIR(目录名(__ FILE__));

#1


24  

That's because your current working directory is the one you call your command at, not the one your script is located in.

那是因为您当前的工作目录是您调用命令的目录,而不是脚本所在的目录。

Use

使用

require __DIR__ . '/../config.php';

instead. __DIR__ is a const that points to the directory current file is located in.

代替。 __DIR__是一个指向当前文件所在目录的const。

#2


6  

One way I do it, is like this:

我这样做的一种方式是这样的:

php -d include_path=/path/to/config.php script.php

-d is used to set INI directives at runtime, so you don't have any changing code/configs/directories.

-d用于在运行时设置INI指令,因此您没有任何更改的代码/配置/目录。

#3


2  

If you don't want to (or can't) change the require line in your code, just cd to the directory that your script expects to be executed within before running your script:

如果您不想(或不能)更改代码中的require行,只需在运行脚本之前cd到脚本期望执行的目录:

cd /path/to
php /path/to/myscript.php

#4


1  

Most likely you got wrong working directory so your relative paths is not pointing where you expect it to. To see how PHP sees it add:

很可能你的工作目录错了,所以你的相对路径没有指向你期望的位置。要了解PHP如何看待它添加:

echo getcwd();

as the 1st line of your script.

作为脚本的第一行。

#5


0  

You need to use absolute path or change working directory:

您需要使用绝对路径或更改工作目录:

chdir(dirname(__FILE__));

CHDIR(目录名(__ FILE__));