How to determine if a PHP file is loaded via cron/command line

前端 未结 4 536
长情又很酷
长情又很酷 2020-12-06 02:45

I need to determine whether the PHP file is being loaded via cron or command line within the code. How can I do this?

相关标签:
4条回答
  • 2020-12-06 03:07

    If you have control over the cron or command, have you considered passing a command-line argument, and reading it with $_SERVER['argv'][0]?

    * * * * *   /usr/bin/php /path/to/script --cron
    

    In the script:

    <?php
    if(isset($_SERVER['argv'][0]) and $_SERVER['argv'][0] == '--cron')
       $I_AM_CRON = true;
    else
       $I_AM_CRON = false;
    
    0 讨论(0)
  • 2020-12-06 03:11

    You can check the PHP_SAPI constant to check if the CLI interpreter is being used:

    $is_cli= PHP_SAPI == 'cli';

    0 讨论(0)
  • 2020-12-06 03:19

    The most reliable and exhaustive way to check where your script is run known to me is

    php_sapi_name()

    Neither this nor any of the other listed methods listed here, however, will give you a distinction between "normal" CLI mode, and a cron call. gahooa's command line argument idea is probably the best and most reliable solution.

    0 讨论(0)
  • 2020-12-06 03:20

    This is one simple way. Certain elements of the $_SERVER array are only set if called from HTTP. Thus you can:

    if(!isset($_SERVER['REQUEST_METHOD'])){
     // from cron or command line
    }else{
     // from HTTP
    }
    

    Others include: $_SERVER['HTTP_HOST']

    0 讨论(0)
提交回复
热议问题