note 117483 added to function.getopt
| From: | housni dot yakoob at NOSPAM dot gmail dot com | Date: | Wed, 17 Jun 2015 11:14:45 +0000 |
| Subject: | note 117483 added to function.getopt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-202881@lists.php.net to get a copy of this message | ||
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.
----
Server IP: 103.11.79.64
Probable Submitter: 124.43.175.208
----
Manual Page -- http://php.net/manual/en/function.getopt.php
Edit -- https://master.php.net/note/edit/117483
Del: integrated -- https://master.php.net/note/delete/117483/integrated
Del: useless -- https://master.php.net/note/delete/117483/useless
Del: bad code -- https://master.php.net/note/delete/117483/bad+code
Del: spam -- https://master.php.net/note/delete/117483/spam
Del: non-english -- https://master.php.net/note/delete/117483/non-english
Del: in docs -- https://master.php.net/note/delete/117483/in+docs
Del: other reasons-- https://master.php.net/note/delete/117483
Reject -- https://master.php.net/note/reject/117483
Search -- https://master.php.net/manage/user-notes.php