tags:

views:

578

answers:

3

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');

the file foo.php will be found when run on the command line, but not when run from a cron script.

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?

+1  A: 

When executed trough a cron job your PHP script probably runs in different context than if you start it manually from the shell. So your relative paths are not pointing to the right path.

Jan Hančič
that's right. In fact, the script's working directory is the working directory of the shell. Should use absolute pathnames.
thephpdeveloper
+1  A: 

Another possibility is that the CLI version is using a different php.ini file. (By default, it'll use php-cli.ini and fallback to the standard php.ini)

Also, if you're using .htaccess files to set your library path, etc. this obviously won't work via the cli.

middaparka
+1  A: 

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
Sjoerd