0
0
PHPprogramming~10 mins

PHP CLI vs web server execution - Interactive Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to print "Hello from CLI" only when running PHP from the command line.

PHP
<?php
if (php_sapi_name() === [1]) {
    echo "Hello from CLI\n";
}
?>
Drag options to blanks, or click blank then click option'
A"cli"
B"cgi"
C"apache"
D"fpm"
Attempts:
3 left
💡 Hint
Common Mistakes
Using "apache" or "cgi" instead of "cli" causes the condition to fail.
2fill in blank
medium

Complete the code to get the current script name differently for CLI and web server.

PHP
<?php
if (php_sapi_name() === "cli") {
    $script = [1];
} else {
    $script = $_SERVER['SCRIPT_NAME'];
}
echo $script . "\n";
?>
Drag options to blanks, or click blank then click option'
A$_SERVER['SCRIPT_FILENAME']
B$_SERVER['PHP_SELF']
C$argv[0]
D$argv[1]
Attempts:
3 left
💡 Hint
Common Mistakes
Using $_SERVER variables in CLI mode returns empty or undefined.
3fill in blank
hard

Fix the error in the code to detect if PHP runs via web server or CLI.

PHP
<?php
if (PHP_SAPI == [1]) {
    echo "Running in CLI mode\n";
} else {
    echo "Running in web server mode\n";
}
?>
Drag options to blanks, or click blank then click option'
A"cli"
Bcli
C"CLI"
D'cli'
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting quotes causes a syntax error or undefined constant error.
4fill in blank
hard

Fill both blanks to create an array with script name and execution mode.

PHP
<?php
$info = [
    'script' => [1],
    'mode' => php_sapi_name() [2] "cli" ? 'CLI' : 'Web'
];
print_r($info);
?>
Drag options to blanks, or click blank then click option'
A$argv[0]
B===
C==
D$_SERVER['SCRIPT_NAME']
Attempts:
3 left
💡 Hint
Common Mistakes
Using == instead of === can cause unexpected results.
5fill in blank
hard

Fill all three blanks to create a message showing execution mode and script name.

PHP
<?php
$mode = php_sapi_name() [1] "cli" ? 'CLI' : 'Web';
$name = [2];
$message = "Running in [3] mode: $name\n";
echo $message;
?>
Drag options to blanks, or click blank then click option'
A==
B$argv[0]
C$_SERVER['SCRIPT_NAME']
Dcli
E"CLI"
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong comparison operator or wrong variable for script name.