Bird
0
0

You want to write a PHP script that behaves differently when run via CLI or web server. Which approach correctly implements this behavior?

hard📝 Application Q15 of 15
PHP - Basics and Execution Model
You want to write a PHP script that behaves differently when run via CLI or web server. Which approach correctly implements this behavior?
ACheck if $_SERVER['HTTP_HOST'] is set to detect web server mode.
BUse php_sapi_name() to detect 'cli' and branch logic accordingly.
CUse isset($_GET) to decide if running on web server.
DRun the script twice, once in CLI and once in web server.
Step-by-Step Solution
Solution:
  1. Step 1: Understand how to detect execution environment

    php_sapi_name() returns 'cli' for CLI mode, which is reliable for branching logic.
  2. Step 2: Evaluate other options

    Checking $_SERVER['HTTP_HOST'] or $_GET is less reliable; running script twice is inefficient.
  3. Final Answer:

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

    php_sapi_name() detects CLI vs web [OK]
Quick Trick: Detect CLI with php_sapi_name() for branching [OK]
Common Mistakes:
  • Relying on $_GET or $_SERVER variables that may not exist
  • Running script multiple times unnecessarily
  • Assuming HTTP_HOST is always set in web server

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes