如果一个PHP脚本被作为cron脚本运行,如果使用相对路径,则包含通常会失败。例如,如果你有:
require_once('foo.php');
在命令行中运行时,文件foo.php可以被找到,但是在cron脚本中运行时却找不到。
通常的解决方法是首先切换到工作目录,或者使用绝对路径。但我想知道的是,cron和shell之间有何不同,导致产生这种行为。为什么在cron脚本中使用相对路径会失败?
如果一个PHP脚本被作为cron脚本运行,如果使用相对路径,则包含通常会失败。例如,如果你有:
require_once('foo.php');
在命令行中运行时,文件foo.php可以被找到,但是在cron脚本中运行时却找不到。
通常的解决方法是首先切换到工作目录,或者使用绝对路径。但我想知道的是,cron和shell之间有何不同,导致产生这种行为。为什么在cron脚本中使用相对路径会失败?
将当前工作目录切换到运行文件的路径。只需使用
chdir(dirname(__FILE__));
include_once '../your_file_name.php'; //we can use relative path after changing directory
在运行文件中使用相对路径,这样您就不需要在每个页面中将相对路径更改为绝对路径。
chdir(__DIR__);
,这样更加简洁。 - But those new buttons though..chdir()
时,此方法才有效。使用include / require dirname(__ FILE__)
更加可靠。 - aequalsb当从cron运行脚本时,脚本的工作目录可能会有所不同。此外,关于PHP的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
require_once(dirname(__FILE__) . '/../setup.php');
dirname( __FILE__ )
__FILE__
是PHP定义的一个常量,表示调用它的文件的完整路径,即使文件是被包含的,__FILE__
仍然会指向文件本身的完整路径--而不是包含该文件的文件。dirname( __FILE__ )
返回包含该文件的目录的完整路径,无论它从何处被包含,而basename( __FILE__ )
则返回文件本身的名称。dirname( __FILE__ )
,将返回“/home/user/public_html/your_directory”,即使活动脚本位于“/home/user/public_html”(请注意末尾斜杠的缺失)。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';
chdir(__DIR__);
chdir()
时,才能执行该操作。 - aequalsb当通过cron作业执行PHP脚本时,与从shell手动启动它的上下文不同。因此,您的相对路径可能不指向正确的路径。
dirname(__FILE__)
。 - aequalsbDIR 能够正常工作,但是在我的本地主机上无法工作,因为它的路径与我的实际网站服务器不同。我使用了以下方法来解决这个问题。
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';
}
dirname(__FILE__)
取代的条件语句。 - aequalsb