PHPverse 2025

Voting

: max(seven, five)?
(Example: nine)

The Note You're Voting On

housni dot yakoob at NOSPAM dot gmail dot com
9 years ago
To elaborate on what 'ch1902' said, there certainly are instances where you may need to execute a script via CLI and the HTTP protocol. In such an instance, you can normalize how your script parses via CLI (using getopt()) as well as via HTTP (using $_GET) with the following simplified code:

<?php
// PHP 5.4+ only due to the new array brace style.
function request(array $options = []) {
// Set the default values.
$defaults = [
'params' => '',
'os' => '',
'username' => posix_getpwuid(posix_geteuid())['name'],
'env' => ''
];
$options += $defaults;

// Sufficient enough check for CLI.
if ('cli' === PHP_SAPI) {
return
getopt('', ['params:', 'os::', 'username::', 'env::']) + $options;
}
return
$_GET + $options;
}

print_r(request());
?>

The above code would yield the results below when access via CLI and HTTP.

/**
* params = foo/bar
* username = housni.yakoob
*/
// CLI
$ php script.php --params=foo/bar --username=housni.yakoob
Array
(
[params] => foo/bar
[username] => housni.yakoob
[os] =>
[env] =>
)

// HTTP
script.php?params=foo/bar&username=housni.yakoob
Array
(
[params] => foo/bar
[username] => housni.yakoob
[os] =>
[env] =>
)

/**
* params = foo/bar
* username = Not provided, therefore, the default value will be used.
*/
// CLI
$ whoami && php script.php --params=foo/bar
housni // <-- Current users usersname (output of `whoami`).
Array
(
[params] => foo/bar
[os] =>
[username] => housni
[env] =>
)

// HTTP
script.php?params=foo/bar
Array
(
[params] => foo/bar
[os] =>
// The username of my Apache user, the result of posix_getpwuid(posix_geteuid())['name']
[username] => www-data
[env] =>
)

As you can see, the output is consistent when the script is executed via the CLI or the web.

<< Back to user notes page

To Top