Bird
0
0

You want a PHP script to execute different logic depending on whether it runs via CLI or a web server. Which approach is the most reliable?

hard📝 Application Q8 of 15
PHP - Basics and Execution Model
You want a PHP script to execute different logic depending on whether it runs via CLI or a web server. Which approach is the most reliable?
ACheck if $_SERVER['HTTP_HOST'] is set to detect web server.
BUse php_sapi_name() === 'cli' to detect CLI and branch logic accordingly.
CUse getenv('SERVER_SOFTWARE') to detect CLI environment.
DCheck if $_ENV['PATH'] contains 'cli'.
Step-by-Step Solution
Solution:
  1. Step 1: Understand detection methods

    php_sapi_name() reliably returns 'cli' when running in CLI mode.
  2. Step 2: Evaluate other options

    $_SERVER['HTTP_HOST'] may not always be set; getenv('SERVER_SOFTWARE') varies; $_ENV['PATH'] is unrelated.
  3. Final Answer:

    Use php_sapi_name() === 'cli' to detect CLI and branch logic accordingly. -> Option B
  4. Quick Check:

    php_sapi_name() is most reliable [OK]
Quick Trick: Use php_sapi_name() for environment detection [OK]
Common Mistakes:
  • Relying on $_SERVER variables that may be missing
  • Using environment variables unrelated to execution mode
  • Assuming presence of HTTP headers in CLI

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes