tags:

views:

327

answers:

3

I'm running a cronjob that calls a php script. I get "failed to open stream" when the file is invoked by cron. When I cd to the directory and run the file from that location, all is well. Basically, the include_once() file that I want to include is two directories up from where the php script resides.

Can someone please tell me how I can get this to work from a cronjob?

+3  A: 

cron is notorious for starting with a minimal environment. Either:

  • have your script set up it's own environment;
  • have a special cron script which sets up the environment then calls your script; or
  • set up the environment within crontab itself.

An example of the last (which is what I tend to use if there's not too many things that need setting up) is:

0 5 * * * (export PATH = /mydir:$PATH ; myexecutable )
paxdiablo
Hi. Thank you for your response. Ehat do you mean by set up the environment? Please elaborate for me. Thanks.
Depends on why it's failing under cron. If it's a missing environment variable, source your .profile. If it's the directory, use "( cd /mydir ; ./myexecutable )" as the command.
paxdiablo
Hey Pax, thanks so much for the help and direction. I couldn't get your solution to work for some reason exporting the path. My server is using BASH which I believe uses the export command but it wouldn't work for some reason. I used soulmerge's solution and just cd'd to the dorectory and then ran the script from there. Worked like a charm.
That's fine. The setting of the path was an example of environment setup, not what you should have done for you particular case. The intent was just to state that cron doesn't provide a very well set up environment in terms of variables or starting directory like your profile does. If you found that running from a specific directory would make it work, then a cd command in the crontab will work (as you've already discovered). Cheers.
paxdiablo
+1  A: 

you need to see what is the path that the cron run from.

 echo pathinfo($_SERVER["PATH_TRANSLATED"]);

according to this do the include

include $path_parts['dirname']."/myfile.php";
Haim Evgi
Hi Haim, thanks for the reply. I never knew about the pathinfo function. This will help me in the future. Thank you!
+2  A: 

There are multiple ways to do this: You could cd into the directory in your cron script:

cd /path/to/your/dir && php file.php

Or point to the correct include file relative to the current script in PHP:

include dirname(__FILE__) . '/../../' . 'includedfile.php';
soulmerge
Hey soulmerge, I believe that the first example will work. I have already tried to use your last suggestion before posting here and couldn't get it working. As Pax said below, cron aparently starts with a minimal env and I never knew that until now. Thanks for this!
Worked like a charm, thanks again soulmerge!