相对路径在 cron PHP 脚本中不起作用
如果 PHP 脚本作为 cron 脚本运行,如果使用相对路径,则包含通常会失败.例如,如果您有
If a PHP script is run as a cron script, the includes often fail if relative paths are used. For example, if you have
require_once('foo.php');
在命令行上运行时会找到文件 foo.php,但在从 cron 脚本运行时不会找到.
the file foo.php will be found when run on the command line, but not when run from a cron script.
对此的典型解决方法是先将 chdir 指向工作目录,或使用绝对路径.但是,我想知道导致这种行为的 cron 和 shell 之间有什么不同.为什么在 cron 脚本中使用相对路径会失败?
A typical workaround for this is to first chdir to the working directory, or use absolute paths. I would like to know, however, what is different between cron and shell that causes this behavior. Why does it fail when using relative paths in a cron script?
推荐答案
从 cron 运行时,脚本的工作目录可能不同.此外,关于 PHP 的 require() 和 include() 存在一些混淆,这导致了工作目录真正是问题所在的混淆:
The working directory of the script may be different when run from a cron. Additionaly, there was some confusion about PHPs require() and include(), which caused confusion about the working directory really being the problem:
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
相关文章