|
|
 |
getopt (PHP 4 >= 4.3.0, PHP 5) getopt -- Obtiene opciones de la lista de argumentos desde la
lÃnea de comandos Descripciónarray getopt ( string opciones )
Devuelve una matriz asociativa con parejas opción /
argumento en base al formato de opciones especificado en
opciones, o FALSE en caso de fallo.
El parámetro opciones puede
contener los siguientes elementos: caracteres individuales, y
caracteres seguidos de dos puntos para indicar que sigue un
argumento que declara una opción. Por ejemplo, la cadena
x reconoce una opción
-x, y una cadena x:
reconoce una opción y un argumento -x
argumento. No importa si un argumento incluye espacio
en blanco al comienzo.
Esta función devolverá una matriz de parejas
opción / argumento. Si una opción no tiene
argumento, el valor será definido a FALSE.
Nota: Esta función no
está implementada en plataformas Windows.
fertugrul [ at ] yahoo [dot] com
05-Jun-2006 02:55
I have written another function to parse command line variables. The source can be found at http://afe.cc/getopt.txt and the include file generic.h is at http://afe.cc/generic.h .
What you need to do is to put required variables to an array in a specific order and call parse_args. All variables that must be read from command line are set automatically. I've tried to imitate the output of GNU's getopt library.
Hope it helps.
AFE
joey at alegria dot co dot jp
30-Apr-2006 09:57
There are 2 simpler (and much faster) methods for getting good getopt() operation without creating your own handler.
1. Use the Console_Getopt PEAR class (should be standard in most PHP installations) which lets you specify both short and long form options as well as whether or not arguments supplied to an option are themselves 'optional'. Very simple to use and requires very little code to operate compaired to writing own handler.
2. If you cannot load external PEAR objects, use your shell's getopt() functions (which in BASHs case work very well) to process options and have your shell script then call your PHP script with a rigid argument structure that is very easy for PHP to digest such as:
% myfile.php -a TRUE -b FALSE -c ARGUMENT ...
If the initial arguments are invalid you can have the shell script return an error without calling the PHP script. Sounds convoluted but is a very simple solution and in fact PHP's own % pear command uses this method. /usr/bin/pear is a shell script that does some simle checking before calling pearcmd.php and repassing the arguments on to it.
The second method is by far the best for portability because it allows a single shell script to check a few things like your PHP version and respond acordingly e.g. does it call your PHP4 or PHP5 compatible script? Also, because getopt() is not available on Windows, The second solution allows you to do Windows specific testing as a BAT file (as oposed to BASH, ZSH or Korn on UNIX).
andrew dot waite at databanx dot net
09-Dec-2005 04:59
After having problems with the getopt() function I developed this to handle parameters in a smilar way to 'nix shell script. Hope this is of some us to someone.
#!/usr/bin/php4
<?php
$i = 1;
$params = array();
for ($i=1; $i < $argc; $i++){
if ( isParam($argv[$i]) ){
if (strlen($argv[$i]) == 1){
}elseif ( strlen($argv[$i]) == 2){
$paramName = $argv[$i];
$paramVal = ( !isParam( $argv[ $i + 1 ] ) ) ? $argv[$i + 1] : null;
}elseif ( strlen($argv[$i]) > 2){
$paramName = substr($argv[$i],0,2);
$paramVal = substr($argv[$i],2);
}
$params[ $paramName ] = $paramVal;
}
}
function isParam($string){
return ($string{0} == "-") ? 1: 0;
}
?>
nutbar at innocent dot com
06-Sep-2005 11:40
The code snippet that daevid at daevid dot com gives works, however is not a perfect getopt replacement since you cannot use the "default" switch statement.
Usage: prog [OPTIONS] <req'd argument> <req'd argument>
The switch() call will eventually run on those 2 required arguments. If you use the "default" statement, it will catch the argument and chances are you use the default statement as your --help trap, thus it will exit the script (if that's what you do).
So, if you use that example below, you may want to check each "argv" variable, and if it doesn't match --*, then you may want to skip past it and store it in another array for retrieval as a required argument if your script uses those.
I will be writing a getopt class that will do everything properly possibly, if/when I do, I'll post it up here so you can all use it rather than the built in getopt code (seems a bit limiting compared to the actual C library getopt_long()).
daevid at daevid dot com
31-May-2005 01:11
This is how I parse command line options:
<?php
$OPTION['debug'] = false;
$OPTION['test'] = false;
$OPTION['force'] = "";
for ($i = 1; $i < $_SERVER["argc"]; $i++)
{
switch($_SERVER["argv"][$i])
{
case "-v":
case "--version":
echo $_SERVER['argv'][0]." v07.19.04 06:10 PM\n";
exit;
break;
case "--debug":
$OPTION['debug'] = true;
break;
case "--force":
$OPTION['force'] = " --force";
break;
case "--db":
case "--database":
case "--id":
if ( is_numeric($_SERVER['argv'][$i+1]) )
$OPTION['CompanyID'] = intval($_SERVER['argv'][++$i]);
else $OPTION['CompanyDB'] = $_SERVER['argv'][++$i];
break;
case "--base":
case "--basedir":
case "--dir":
$OPTION['basedir'] = $_SERVER["argv"][++$i];
break;
case "--test":
$OPTION['test'] = true;
break;
case "-?":
case "-h":
case "--help":
?>
This will print any .txt files, process any .sql files and
execute any .php files found starting from the base directory
'<?=$OPTION['basedir']?>' in alphabetical order.
Usage: <?php echo $_SERVER['argv'][0]; ?> <option>
--help, -help, -h, or -? to get this help.
--version to return the version of this file.
--debug to turn on output debugging.
--test to fake the SQL and PHP commands.
--force to ignore SQL errors and keep on going.
--db [CompanyDB] to apply to only this [CompanyDB].
--id [CompanyID] to apply to only this [CompanyID].
--basedir [directory] to change base directory from <?=$OPTION['basedir']?>.
Omitting the CompanyID or CompanyDB will cause ALL Company DB's to be updated.
There are global files and per-company files. Global files are applied to global
databases (see list below). Their filename contains a tag that reflects the database
to apply them against. Per-company files are applied against databases. Their
filename contains a tag that reads 'COMPANY'. Files should be in <?=$OPTION['basedir']?>;
Global files that are understood:
<?=$OPTION['basedir']?>
<?php foreach ($GLOBAL_SQL_FILES as $sqlFile) echo $sqlFile." "; ?>
<?php
exit;
break;
}
} ?>
dante at wiw dot org
30-Jan-2005 08:44
i didn't like the way getopt worked, exactly, so i wrote a new variant, that other people would possibly like to see. (works more like perl's function)
it reads an array of options like:
$opAr = array ("-a|--append","-l|--list","-i|--input:");
$op = bgetop($opAr);
and parses the command line, returning an array like
$op['cmdline'] = $param; ...
it has a small bug that can easily be avoided ... haven't yet determined how to work around the particular case where the bug exists, but otherwise is very robust.
it also accepts wildwards as the last option, or the output from another program like 'find' :
./getop.php `find /etc -name *.conf`
populates the $op array with the filenames returned from find. it's pretty nifty.
the source is at : http://higginsforpresident.net/projects/source/getopt-0.1.phps
i didn't want to post it here until i fixed that one condition, but the function works nicely (as expected) if you don't use duplicate beginnings for different option array strings:
$opAr = array("-f:","--foo");
bgetopt() sees --foo needs no 'next input', but -f exists in '--foo', so ./getop.php -f foobar set's f to 'true', which is the
expected result of array("-f","--foo") or array("-f|--foo"), but not ("-f:","--foo");
enjoy. (my first submission here ... be kind.)
grange
15-Oct-2004 07:50
getopt() will return an empty array if you call it more than once.
vedanta at maintec dot com
12-May-2004 02:36
A sample use :
#!/usr/bin/php
<?php
$opt = getopt("s:f:r:u:");
$help="***Error :url_mailer.php -s <subject> -f <sender_email> -r <receipient_email> -u <url_to_mail>";
if($opt[s]=='' || $opt[r]=='' || $opt[u]=='' || $opt[f]=='' ){ echo "$help\n";exit(); }
$url=trim($opt[u]);
$message=file_get_contents($url);
$headers = "MIME-Version: 1.0\r\n";
$headers.= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers.= "From: $opt[f] \r\n";
mail($opt[r],$opt[s],$message,$headers);
?>
chris at tiny dot net
23-Apr-2004 07:17
"phpnotes at kipu dot co dot uk" and "tim at digicol dot de" are both wrong or misleading. Sean was correct. Quoted space-containing strings on the command line are one argument. It has to do with how the shell handles the command line, more than PHP. PHP's getopt() is modeled on and probably built upon the Unix/POSIX/C library getopt(3) which treats strings as strings, and does not break them apart on white space.
Here's proof:
$ cat opt.php
#! /usr/local/bin/php
<?php
$options = getopt("f:");
print_r($options);
?>
$ opt.php -f a b c
Array
(
[f] => a
)
$ opt.php -f 'a b c'
Array
(
[f] => a b c
)
$ opt.php -f "a b c"
Array
(
[f] => a b c
)
$ opt.php -f a\ b\ c
Array
(
[f] => a b c
)
$
klewan at chello dot at
19-Dec-2003 08:00
For all buddies outside who dont get getopt to work :)
here is a php variant with just standard function calls
<?
$options["a"]="valA";
$options["b"]="valB";
parseArgs($argv,&$options);
if($options["h"] == true) {
print_usage();
exit(1);
}
var_dump($options);
function parseArgs($a = array(), $r) {
$f=NULL;
for($x = 0; $x < count($a); $x++) {
if($a[$x]{0} == "-") {
$f=$a[$x];
$r[substr($f,1,strlen($f))]=true;
}
if ($f != NULL) {
if (($a[$x+1] != NULL) && ($a[$x+1] != "") && ($a[$x+1] != "") && ($a[$x+1]{0} != "-")) {
$r[substr($f,1,strlen($f))]=$a[$x+1];
} else {
$f=$a[x+1];
}
}
}
}
function print_usage() {
echo "-a bla bla\n";
echo "-b bla bla\n";
echo "-h display this help\n";
}
?>
carl at thep dot lu dot se dot nospam
17-Jul-2003 07:07
Unlike POSIX.2 getopt(), this function does not modify argv, so it's
only useful if you have no non-option arguments. More often than
not, you're probably better off examining $argv yourself.
| |
| | Citas célebres | Cualquier traje es un disfraz, ¿o no? Excepto nuestra piel natural, claro. George Bernard Shaw Dramaturgo inglés (1856-1950) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Parecidos razonables | | Panadero | - ¿Por qué a ese ladrón le llaman "El Panadero"?
- Porque siempre lo cogen con las manos en la masa. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|