Running php from cron did not run as CLI

I noticed this problem after running php script from cron to timeout, but this is not a problem when it was started manually from the command line. (PHP has max_execution_time for the CLI by default)

So, I tried to run a simple cron like this:

50 8 * * * php -q /tmp/phpinfo.php > /tmp/phpinfo 

the script will just call phpinfo ().

Surprisingly, he wrote phpinfo in html format, which suggested that it was not run as a CLI. And max_execution_time was 30 in the output.

Running the script manually from the command line, such

 php -q /tmp/phpinfo.php | less 

I wrote out information about php in text format, and max_execution_time - 0 at the output.

I know there is a configuration issue somewhere, but I just couldn't find where the problem is. This happens on a production server, on which I have full control. Running the same script from cron on my development machine worked fine.

Here is a summary of the difference

 function | CLI | cron | php_sapi_name | cli | cgi-fcgi | php_ini_loaded_file | /usr/local/lib/php.ini | /usr/local/lib/php.ini | 
+6
source share
1 answer

I suspect your problem lies in the missing environment variable, namely the important $PATH . When you run this:

 php -q /tmp/phpinfo.php 

the system should decide which program you mean by php . He does this by looking, in order, through the directories in the current $PATH environment variable.

Executed from a normal shell, your environment is configured in such a way that it finds the CLI version of PHP, as you expect.

However, when cron executes the command, it does this without any environment variables that will be configured by your interactive shell. Since your system may have other executables, called php , for different "SAPIs", it may choose "incorrect" - in your case, the cgi-fcgi , in accordance with the message you output from php_sapi_name() .

To fix this, first find the path to the correct php executable in the normal shell by typing this:

 which php 

This should give you a path like /usr/bin/php . You can go ahead and check if this is a "symbolic link" pointing to a different file name:

 ls -l $(which php) 

(you will see an arrow on the output if there is one, for example /usr/bin/php -> /usr/bin/php5-cli )

Then, take this full path to the PHP executable and use it in your crontab entry so that it looks something like this:

 50 8 * * * /usr/bin/php5-cli -q /tmp/phpinfo.php > /tmp/phpinfo 
+14
source

Source: https://habr.com/ru/post/957867/


All Articles