如果PHP脚本作为cron脚本运行,则如果使用相对路径,则包含通常会失败。例如,如果你有
require_once('foo.php');
在命令行上运行时会找到文件foo.php,但在从cron脚本运行时则不会找到。
这种方法的典型解决方法是首先将chdir添加到工作目录,或使用绝对路径。但是,我想知道导致此行为的cron和shell之间有什么不同。为什么在cron脚本中使用相对路径时会失败?
答案 0 :(得分:95)
将工作目录更改为正在运行的文件路径。只需使用
chdir(dirname(__FILE__));
include_once '../your_file_name.php'; //we can use relative path after changing directory
运行文件中的。然后,您不需要在每个页面中更改绝对路径的所有相对路径。
答案 1 :(得分: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
答案 2 :(得分:7)
我得到“require_once”同时使用cron和apache的唯一机会是
require_once(dirname(__FILE__) . '/../setup.php');
答案 3 :(得分:4)
因为cron作业的“当前工作目录”将是crontab文件所在的目录 - 所以任何相对路径都与THAT目录相关。
处理它的最简单方法是使用dirname()
函数和PHP __FILE__
常量。否则,只要将文件移动到不同的目录或具有不同文件结构的服务器,就需要使用新的绝对路径编辑文件。
dirname( __FILE__ )
__FILE__
是由PHP定义的常量,作为调用它的文件的完整路径。即使包含该文件,__FILE__
也将始终引用文件本身的完整路径 - 而不是执行包含的文件。
所以dirname( __FILE__ )
返回包含该文件的目录的完整目录路径 - 无论它包含在哪里,basename( __FILE__ )
都会返回文件名。
例如: 让我们假装“/home/user/public_html/index.php”包含“/home/user/public_html/your_directory/your_php_file.php”。
如果你在“your_php_file.php”中调用dirname( __FILE__ )
,即使活动脚本位于“/ home / user / public_html”,也会返回“/ home / user / public_html / your_directory”(注意缺席尾随斜线)。
如果您需要INCLUDING文件的目录,请使用:dirname( $_SERVER['PHP_SELF'] )
,它将返回“/ home / user / public_html”,并且与在“index.php”文件中调用dirname( __FILE__ )
相同相对路径是相同的。
示例用法:
@include dirname( __FILE__ ) . '/your_include_directory/your_include_file.php';
@require dirname( __FILE__ ) . '/../your_include_directory/your_include_file.php';
答案 4 :(得分:3)
另一种可能性是CLI版本使用不同的php.ini文件。 (默认情况下,它将使用php-cli.ini并回退到标准的php.ini)
另外,如果您使用.htaccess文件来设置库路径等,这显然无法通过cli工作。
答案 5 :(得分:2)
除了上面接受的答案外,您还可以使用:
chdir(__DIR__);
答案 6 :(得分:1)
当通过cron作业执行时,PHP脚本可能在不同的上下文中运行,而不是从shell手动启动它。所以你的相对路径并没有指向正确的路径。
答案 7 :(得分:0)
DIR可以工作,虽然它不能在我的localhost上运行,因为它的路径与我的实时站点服务器不同。我用它来修复它。
if(__DIR__ != '/home/absolute/path/to/current/directory'){ // path for your live server
require_once '/relative/path/to/file';
}else{
require_once '/absolute/path/to/file';
}