Challenge - 5 Problems
PHP CLI vs Web Server Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output difference between CLI and web server
What is the output of this PHP code when run from the command line (CLI) versus when accessed via a web server?
PHP
<?php if (php_sapi_name() === 'cli') { echo "Running in CLI mode"; } else { echo "Running in Web Server mode"; }
Attempts:
2 left
💡 Hint
php_sapi_name() returns the interface PHP is using.
✗ Incorrect
php_sapi_name() returns 'cli' when run from the command line, so the code prints 'Running in CLI mode'. When run via a web server, it returns something else like 'apache2handler'.
🧠 Conceptual
intermediate2:00remaining
PHP environment variables in CLI vs Web Server
Which statement about environment variables in PHP CLI and web server execution is true?
Attempts:
2 left
💡 Hint
Think about where PHP gets environment variables in each mode.
✗ Incorrect
In CLI mode, PHP inherits environment variables from the shell or terminal. In web server mode, environment variables depend on the server's configuration and may differ.
🔧 Debug
advanced2:00remaining
Why does PHP script behave differently in CLI and web server?
A PHP script uses $_SERVER['REQUEST_METHOD'] to check the HTTP method. It works fine on the web server but throws an error in CLI. Why?
PHP
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { echo "Form submitted"; } else { echo "Show form"; }
Attempts:
2 left
💡 Hint
Check if $_SERVER['REQUEST_METHOD'] exists in CLI mode.
✗ Incorrect
$_SERVER['REQUEST_METHOD'] is set only in web server context during HTTP requests. In CLI, it is not set, so accessing it causes an undefined index error.
📝 Syntax
advanced2:00remaining
Which PHP code snippet correctly detects CLI mode?
Choose the code snippet that correctly detects if PHP is running in CLI mode.
Attempts:
2 left
💡 Hint
Check for correct comparison operator and case sensitivity.
✗ Incorrect
PHP_SAPI is a predefined constant with the current interface name. Comparing it with 'cli' using === is correct. Option B uses == which works but === is preferred. Option B uses assignment = instead of comparison. Option B compares with uppercase 'CLI' which is incorrect.
🚀 Application
expert2:00remaining
How to write a PHP script that behaves differently in CLI and web server?
You want a PHP script to print 'Hello CLI' when run from command line and 'Hello Web' when accessed via web server. Which code achieves this?
Attempts:
2 left
💡 Hint
Use php_sapi_name() to detect CLI mode exactly.
✗ Incorrect
php_sapi_name() returns 'cli' when run from command line. Option C correctly checks for 'cli' and prints accordingly. Option C checks for 'web' which is not a valid sapi name. Option C reverses logic and misuses $_SERVER['HTTP_HOST']. Option C checks for 'cgi' which is not CLI.