6

How can I distinguish whether a function is called from drush or by a real HTTP request?

3

Drush is PHP executed over the CLI (Command Line Interface), so perhaps this question can help.

| improve this answer | |
  • In the unlikely event that cron.php was invoked over php-cli, this approach will yield a false positive. – aaronbauman Nov 27 '13 at 16:22
8

From drush.php:

function_exists('drush_main') may be used by modules to detect whether they are being called from drush. See http://drupal.org/node/1181308 and http://drupal.org/node/827478

| improve this answer | |
5

In Drupal 7:

if (drupal_is_cli()) {
  // Cli only code here
}

if you want to specifically check for drush use the above along with a check for drush_main.

if (drupal_is_cli() && function_exists('drush_main')) {}

In Drupal 8

if (PHP_SAPI == 'cli') {
  // CLI only code here
}

Changelog for D8: https://www.drupal.org/node/2295037

| improve this answer | |
0

Request from command line

For Drupal 7, use drupal_is_cli()

For Drupal 5, 6 and 8, use PHP_SAPI == 'cli'

Request from drush

Always use function_exists('drush_main')

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.