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
function getoptreq ($options, $longopts)
{
if (PHP_SAPI === 'cli' || empty($_SERVER['REMOTE_ADDR'])) {
return getopt($options, $longopts);
}
else if (isset($_REQUEST)) {
$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) === '::') {
$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) === ':') {
$key = substr($opt, 0, -1);
if (isset($_REQUEST[$key]) && !empty($_REQUEST[$key]))
$found[$key] = $_REQUEST[$key];
}
else if (ctype_alnum($opt)) {
if (isset($_REQUEST[$opt]))
$found[$opt] = false;
}
}
return $found;
}
return false;
}
?>
Example
<?php
$opts = getoptreq('abc:d:e::f::', array('one', 'two', 'three:', 'four:', 'five::'));
var_dump($opts);
?>