相对路径在cron PHP脚本中不起作用

Sjo*_*erd 48 php cron

如果PHP脚本作为cron脚本运行,则如果使用相对路径,则包含通常会失败.例如,如果你有

require_once('foo.php');
Run Code Online (Sandbox Code Playgroud)

在命令行上运行时将找到文件foo.php,但在从cron脚本运行时则不会找到.

一个典型的解决方法是首先将chdir添加到工作目录,或使用绝对路径.但是,我想知道导致此行为的cron和shell之间有什么不同.为什么在cron脚本中使用相对路径时会失败?

小智 97

将工作目录更改为正在运行的文件路径.只是用

chdir(dirname(__FILE__));
include_once '../your_file_name.php'; //we can use relative path after changing directory
Run Code Online (Sandbox Code Playgroud)

在运行文件中.然后,您不需要在每个页面中更改所有相对路径到绝对路径.

  • 你也可以使用`chdir(__ DIR __);`这里更简洁一些. (2认同)

Sjo*_*erd 12

从cron运行时,脚本的工作目录可能不同.另外,有一些关于PHPs require()和include()的混淆,这引起了对工作目录的困惑:

include('foo.php') // searches for foo.php in the same directory as the current script
include('./foo.php') // searches for foo.php in the current working directory
include('foo/bar.php') // searches for foo/bar.php, relative to the directory of the current script
include('../bar.php') // searches for bar.php, in the parent directory of the current working directory
Run Code Online (Sandbox Code Playgroud)


小智 7

我得到"require_once"同时使用cron和apache的唯一机会是

require_once(dirname(__FILE__) . '/../setup.php');
Run Code Online (Sandbox Code Playgroud)


aeq*_*lsb 5

因为cron作业的“当前工作目录”将是crontab文件所在的目录-因此,任何相对路径都相对于THAT目录。

处理此问题的最简单方法是使用dirname()函数和PHP __FILE__常量。否则,每当您将文件移动到其他目录或具有不同文件结构的服务器时,都需要使用新的绝对路径来编辑文件。

dirname( __FILE__ )
Run Code Online (Sandbox Code Playgroud)

__FILE__是一个常量,由PHP定义为从中调用它的文件的完整路径。即使包含了文件,__FILE__也将始终引用文件本身的完整路径,而不是引用包含文件。

因此,dirname( __FILE__ )将完整目录路径返回到包含文件的目录-不管它是从哪里包含的,并basename( __FILE__ )返回文件名本身。

示例:假设“ /home/user/public_html/index.php”包括“ /home/user/public_html/your_directory/your_php_file.php”。

如果调用dirname( __FILE__ )“ your_php_file.php”,则即使活动脚本位于“ / home / user / public_html”中,也会返回“ / home / user / public_html / your_directory”(请注意,不带斜杠)。

如果您需要包含文件的目录,请使用:dirname( $_SERVER['PHP_SELF'] )将返回“ / home / user / public_html”,并且与调用dirname( __FILE__ )“ index.php”文件相同,因为相对路径相同。

用法示例:

@include dirname( __FILE__ ) . '/your_include_directory/your_include_file.php';

@require dirname( __FILE__ ) . '/../your_include_directory/your_include_file.php';
Run Code Online (Sandbox Code Playgroud)