note 113015 added to function.getopt
| From: | ch1902 | Date: | Sun, 18 Aug 2013 15:37:06 +0000 |
| Subject: | note 113015 added to function.getopt | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-196007@lists.php.net to get a copy of this message | ||
Sometimes you will want to run a script from both the command line and as a web page, for example to
debug with better output or a command line version that writes an image to the system but a web
version that prints the image in the browser. You can use this function to get the same options
whether passed as command line arguments or as $_REQUEST values.
<?php
/**
* Get options from the command line or web request
*
* @param string $options
* @param array $longopts
* @return array
*/
function getoptreq ($options, $longopts)
{
if (PHP_SAPI === 'cli' || empty($_SERVER['REMOTE_ADDR'])) // command line
{
return getopt($options, $longopts);
}
else if (isset($_REQUEST)) // web script
{
$found = array();
$shortopts = preg_split('@([a-z0-9][:]{0,2})@i', $options, 0,
PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$opts = array_merge($shortopts, $longopts);
foreach ($opts as $opt)
{
if (substr($opt, -2) === '::') // optional
{
$key = substr($opt, 0, -2);
if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
$found[$key] = $_REQUEST[$key];
else if (isset($_REQUEST[$key]))
$found[$key] = false;
}
else if (substr($opt, -1) === ':') // required value
{
$key = substr($opt, 0, -1);
if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
$found[$key] = $_REQUEST[$key];
}
else if (ctype_alnum($opt)) // no value
{
if (isset($_REQUEST[$opt]))
$found[$opt] = false;
}
}
return $found;
}
return false;
}
?>
Example
<?php
// php script.php -a -c=XXX -e=YYY -f --two --four=ZZZ --five=5
// script.php?a&c=XXX&e=YYY&f&two&four=ZZZ&five=5
$opts = getoptreq('abc:d:e::f::', array('one', 'two',
'three:', 'four:', 'five::'));
var_dump($opts);
/**
array(7) {
'a' => bool(false)
'c' => string(3) "XXX"
'e' => string(3) "YYY"
'f' => bool(false)
'two' => bool(false)
'four' => string(3) "ZZZ"
'five' => string(1) "5"
}
*/
?>
----
Server IP: 87.124.126.49
Probable Submitter: 94.4.195.68
----
Manual Page -- http://php.net/manual/en/function.getopt.php
Edit -- https://master.php.net/note/edit/113015
Del: integrated -- https://master.php.net/note/delete/113015/integrated
Del: useless -- https://master.php.net/note/delete/113015/useless
Del: bad code -- https://master.php.net/note/delete/113015/bad+code
Del: spam -- https://master.php.net/note/delete/113015/spam
Del: non-english -- https://master.php.net/note/delete/113015/non-english
Del: in docs -- https://master.php.net/note/delete/113015/in+docs
Del: other reasons-- https://master.php.net/note/delete/113015
Reject -- https://master.php.net/note/reject/113015
Search -- https://master.php.net/manage/user-notes.php