How to get fopen to work with crontab

Basically you need to understand three things to understand how this works: 1) Which user is the php file running as? - When you run "crontab -e" the user you are running it as will be the user the php file runs as. 2) What are the permissions on the log file? - Check the permissions, owner and group using "ls -al" 3) What are the permissions on the php file? If you run the php file with a directive #!/bin/php at the top of the file then you need to set executable permissions on the file. If you specify php /path/to/phpfile.php then you don't need to do this. If you still can't get it going then here are some troubleshooting tips. In the crontab file you have: * * * * * /var/www/foo/bar/test.php as the command to execute. Set yourself to root: $ sudo /bin/bash Then when running this from the command line you'll see: root@vps:~# /var/www/foo/bar/cron/test.php bash: /var/www/foo/bar/cron/test.php: Permission denied This is because the file doesn't have the executable flag: ($ ls -al) -rw-r--r-- 1 user1 user1 403 Nov xx 14:48 /var/www/foo/bar/cron/test.php After setting the executable flag: root@vps:~# chmod +x /var/www/foo/bar/cron/test.php root@vps:~# ls -la /var/www/foo/bar/cron/test.php -rwxr-xr-x 1 user1 user1 403 Nov 16 14:48 /var/www/foo/bar/cron/test.php The script works properly from the shell when running it directly, and also works from crontab. Alternatively you could change the command line portion of your crontab configuration to say (I didn't test this exact scenario but there is no reason why it wouldn't work) : php /var/www/foo/bar/cron/test.php So basically, the problem there is trying to execute a file which wasn't executable. Also, something useful for reference - you can log the output of your crontab scripts using 1> and 2> to redirect to a log file. 1> is for the standard output, 2> is for the error output. So for example if you had the following line in your cron config: * * * * * /var/www/foo/bar/cron/test.php 1> /root/standard.out 2> /root/error.out You would get any messages outputted to the standard output in the file /root/standard.out, and any messages outputted to the error output to /root/error.out. This is handy when trying to troubleshoot cron jobs. Of course you need to ensure that the user running the cron job can write to the files that you attempt to log to.

Comments

Popular posts from this blog

PHP timezones explained

iPhone Internet Tethering settings