Bird
0
0

You have a PHP script that logs messages differently when run via CLI or web server. Which code snippet correctly implements this behavior?

hard📝 Application Q9 of 15
PHP - Basics and Execution Model
You have a PHP script that logs messages differently when run via CLI or web server. Which code snippet correctly implements this behavior?
Aif (php_sapi_name() === 'cli') { error_log('CLI log'); } else { error_log('Web log'); }
Bif (php_sapi_name() = 'cli') { error_log('CLI log'); } else { error_log('Web log'); }
Cif ($_SERVER['REMOTE_ADDR']) { error_log('CLI log'); } else { error_log('Web log'); }
Dif (getenv('SERVER_SOFTWARE') === 'cli') { error_log('CLI log'); } else { error_log('Web log'); }
Step-by-Step Solution
Solution:
  1. Step 1: Validate condition syntax

    if (php_sapi_name() === 'cli') { error_log('CLI log'); } else { error_log('Web log'); } uses correct strict comparison and function.
  2. Step 2: Evaluate other options

    if (php_sapi_name() = 'cli') { error_log('CLI log'); } else { error_log('Web log'); } uses assignment instead of comparison; C incorrectly uses REMOTE_ADDR; D misuses SERVER_SOFTWARE.
  3. Final Answer:

    Option A correctly implements CLI vs web logging. -> Option A
  4. Quick Check:

    Use strict comparison and php_sapi_name() [OK]
Quick Trick: Use php_sapi_name() === 'cli' for logging [OK]
Common Mistakes:
  • Using assignment '=' instead of comparison
  • Checking wrong server variables
  • Assuming environment variables indicate CLI

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes