Issue
How to run PHP from a cronjob?
Some PHP scripts executed with cronjobs are not working properly, are interrupted, or just hang. Known affected website engines: Magento, CakePHP.
Environment
CloudLinux OS 6(h)/7(h)/8
cPanel/Plesk/DirectAdmin/No panel
Solution
There are several ways to resolve the issue depending on which panel is used or if you edit cronjob via command line. Call PHP CLI binary manually:
* * * * * /usr/local/bin/php /home/user/cronjob.php
Add /usr/local/bin/ to users crontab as:
PATH="/usr/local/bin/:/usr/bin:/bin" * * * * * php /home/user/cronjob.php
Force export path variable right before executing PHP script:
* * * * * export PATH=$PATH:/usr/local/bin; php /home/user/cronjob.php
Note 1: Engines like CakePHP use app/Console/cake wrapper to define which PHP to call. You may need to modify the file, and point to /usr/local/bin/php manually.
Note 2: On DirectAdmin panel to force specified path to be used for user cron jobs you have to create /usr/local/directadmin/data/templates/custom/cron_template.txt with the following content:
PATH=/usr/local/bin:/usr/local/sbin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin SHELL=/bin/sh MAILTO=|EMAIL| |CRONS|
More: https://www.directadmin.com/features.php?id=621
Cause
The issue is caused by PHP CGI binary is being called instead of PHP CLI version. It happens due to PATH environment variable does not contain /usr/local/bin/.
Comments
1 comment
Under EasyApache4, using /usr/local/bin/php will still run the PHP script using the default/native version of PHP. If the account is using PHP Selector and has PHP 7.2 selected (for example) but the Native version on the cPanel server is set to 5.6, then the customer will be running 5.6 on their crons. To fix this, the customer should, instead, use the full path to the alt-php version... in this case, they would set their cron to: "/opt/alt/php72/usr/bin/php somescript.php"
Please sign in to leave a comment.