Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Cron Job: Including file not working?

Tags:

include

php

cron

i run a cron job every night, but for some reason, it is saying that the file i try to include is inexistant:

Warning: require(../includes/common.php): failed to open stream: No such file or directory in /home/fini7463/public_html/cron/journeyNotifications.php on line 2
Fatal error: require(): Failed opening required '../includes/common.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/fini7463/public_html/cron/journeyNotifications.php on line 2

here's the code:

set_include_path('/home/fini7463/public_html/includes/');
require 'common.php';

the file 'common.php' is located as follows

public_html => cron     => journeyNotifications.php
            => includes => common.php

i even set the include path (as shown in the code), but i am still getting this error. what could the problem be?

thanks!

like image 526
gsquare567 Avatar asked Jun 29 '10 12:06

gsquare567


2 Answers

If you do require('../includes/common.php'), the path is traversed relative to the current working directory.

If you do require('common.php'), the file is searched in the include path, and in the directory of the script which calls the require().

To solve this, first change directory in your crontab:

cd /home/fini7463/public_html; php -f cronjob.php
like image 118
Sjoerd Avatar answered Nov 19 '22 14:11

Sjoerd


Calling set_include_path() as you do trashes the previous path. The call replaces the previous path with whatever you're passing as an argument, so if any of your code loads other libraries (ie: PEAR/PECL modules), they'll no longer be accessible as you've trashed the include path. You should use:

set_include_path(get_include_path() . PATH_SEPARATOR . '/home/fini7463/public_html/includes/');

That will append your new path to the include path.

As well, you can never quite tell what the working directory will be when cron fires up your script. It could be the home directory of the user you're running the script as, could be /tmp, or some other directory entirely. If you want to use relative paths in the script for anything, you'll have to make sure the working directory is set to a known value. Either by using a 'cd' in the crontab, or using a 'chdir' inside the script before doing anything involving the relative paths.

like image 3
Marc B Avatar answered Nov 19 '22 15:11

Marc B