1

I have a php script that sends out a email report with an attached pdf document. I use fopen. If I call the php file manualy it works without any problems and the mails are beeing send as expected.

But: If the same file should is call by cron job, it does not work at all. The error is: Warning: fopen(filename.pdf): failed to open stream: No such file or directory in /home/public_html/util.php on line 29

Any ideas how to fix this?

Gregor Meier
  • 13
  • 1
  • 3

2 Answers2

2

Every cron runs in a minimal environment, which can be a different shell and a different profile than your user account. Also scripts are started not from the containing directory themselves.

In most cases it works, if you just change your directory to the one containing the script like you do when execute the script on the command line shell. Instead of

* * * * * /usr/bin/php /path/to/your/file.php

write this:

* * * * * cd /path/to/your/ && /usr/bin/php ./file.php

If this is not sufficient, you can load your default user shell and your PATH variable with writing

SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

at the top of your crontab (with the right settings of course, which might be /bin/bash and the output of echo $PATH).

Ulrich Thomas Gabor
  • 6,584
  • 4
  • 27
  • 41
1

Cron jobs run without any environment, including a current directory. That means that you'll need to use the full path to any files that you want to work with.

If you add a valid email address at the top of your crontab:

MAILTO=your-email@example.com

you'll get any output the cron job does sent to your email. This includes error messages, which can be useful for debugging.

thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • [They have a minimum environment.](http://askubuntu.com/a/23438) – Ulrich Thomas Gabor Aug 14 '14 at 09:00
  • Indeed they do, although I never remember what that environment is, and sometimes the defaults are just wrong... I've always found it more productive to pretend I need to set everything up myself ;-) – thebjorn Aug 14 '14 at 09:07