6

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

4 Answers 4

3

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

1
  • In the unlikely event that cron.php was invoked over php-cli, this approach will yield a false positive. Nov 27, 2013 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

6

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

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')

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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