To allow a "zero" option value:
replace:
$ret['options'][$com] = !empty($value) ? $value : true;
by:
$ret['options'][$com] = (strlen($value) > 0 ? $value : true);
In the sample below.
Thanks to Chris Chubb to point me out the problem
Usando PHP desde la lÃnea de comando
Desde la versión 4.3.0, PHP soporta un nuevo tipo de SAPI (Interfaz De Programación De Uso Del Servidor) llamada CLI que significa literalmente interfaz de lÃnea de comando (Command Line Interface). Como el nombre implica, este tipo de SAPI se foca en la creación de aplicaciones que pueden correr desde la lÃnea de comando (o desde el desktop también) con PHP. Hay algunas diferencias dentro del CLI SAPI y otros SAPI que son explicadas en este capÃtulo. Es importante mencionar que CLI y CGI son diferentes clases de SAPI y comparten algunas caracterÃsticas.
La interfaz llamada CLI SAPI fue introducida con PHP 4.2.0, pero es todavÃa en estado experimental y tiene que ser activada explÃcitamente con --enable-cli cuando usando ./configure. Desde PHP 4.3.0 la interfaz CLI SAPI es activada automáticamente. Tu puedes usar --disable-cli para de-activarla.
Desde PHP 4.3.0, el nombre, locación, y existencia de los binarios CLI/CGI serán diferentes dependiendo en como Instales PHP en tu sistema. Cuando ejecutes make, CGI, y CLI son compilados automáticamente, y puestas como sapi/cgi/php y sapi/cli/php respectivamente, en el directorio "source" de PHP. Debes notar, que los dos son llamados php. Lo que ocurre durante el proceso make depende en tu lÃnea de configuración (./configure). Si el modulo SAPI es seleccionado durante tu configuración, como por ejemplo apxs, o la opción --disable-cgi es usada, el CLI es copiado a {PREFIX}/bin/php durante la ejecución del comando make install de otras maneras el CGI es instalado aquÃ. Por ejemplo, si pones --with-apxs en tu configuración, entonces el CLI es copiado a {PREFIX}/bin/php durante make install. Si tu quieres sobrescribir la instalación del CGI binario, utiliza make install-cli después de usar make install. Alternativamente puedes especificar --disable-cgi en tu lÃnea de configuración.
Note: Por que ambos --enable-cli y --enable-cgi son activados automáticamente, simplemente teniendo --enable-cli en tu lÃnea de configuración no necesariamente significa que CLI son copiados a {PREFIX}/bin/php durante make install.
Los archivos de PHP 4.2.0 y PHP 4.2.3 distribuÃan el CLI como php-cli.exe, y los mantenÃa en el mismo directorio que el CGI php.exe. Empezando con PHP 4.3.0 el archivo para windows distribuye el CLI como php.exe en un directorio llamado cli; o sea cli/php.exe.
Note: Que versión de SAPI tengo?
Desde tu lÃnea de comando, ejecutando php -v te dejara saber si php es CGI o CLI.
Diferencias remarcables del CLI SAPI comparadas con otros SAPIs: SAPIs:
-
En esta clase de CGI SAPI no hay cabeceras ("headers") escritas en el resultado ("output").
Aunque el CGI SAPI provee una manera de suprimir HTTP cabeceras ("headers"), no existe una opción equivalente que los activa en el CLI SAPI.
CLI automáticamente empieza en modo silencioso, la opción -q existe por compatibilidad con antiguos programas CGI.
No cambia el directorio corriente, a ese en el cual el programa vive. La opción -C es mantenida por compatibilidad.
Errores son reportados en texto, no en el formato HTML.
-
Hay ciertas directivas en el php.ini que son sobrescrita por el CLI SAPI por que estas no hacen mucho sentido en situaciones donde la lÃnea de comando es usada:
Directivas sobrescrita en php.ini Directivas (directives) CLI SAPI evaluó automático (default value) Commentario (comment) html_errors FALSE Cuando los resultados incorrectos aparecen en tu lÃnea de comando, puede ser difÃcil hacer sentido de ellos con todas esas HTML tags, por esta razón, esta directiva es automáticamente FALSE. implicit_flush TRUE Es deseoso que los resultados de print (imprimir)(), echo (ecco)() y otras relacionadas, sean inmediatamente escritas como resultados y no mantenidas en ningún buffer. Tu todavÃa puedes usar output buffering si tu quieres manipular los resultados proveidos automáticamente. max_execution_time 0 (unlimited) Debido un numero ilimitado de posibilidades de usar PHP en la lÃnea de comando, el máximo tiempo de ejecución es ilimitado. Aunque aplicaciones escritas para el Internet, usualmente requieres una rápida ejecución, la clase de aplicación que es ejecutada desde la lÃnea de comando, usualmente necesitan mas tiempo para ejecutar correctamente. register_argc_argv TRUE Por que estas opciones son TRUE tu siempre necesitaras acceso al argc (el numero de argumentos pasados a la aplicación) y argv (el array de argumentos) en el CLI SAPI.
Desde la versión 4.3.0 de PHP, las variables $argc y $argv son registradas y llenadas con los resultados apropiados cuando usando CLI SAPI. Antes de esta versión, la creación de estas variables es similar a como en CGI y MODULE versiones que requiere la PHP directiva register_globals estar on (active). Sin importar la versión o la configuración de register_globals tu siempre puedes trabajar por medio de $_SERVER o $HTTP_SERVER_VARS. Por ejemplo: $_SERVER['argv']
Note: Estas instrucciones no pueden ser iniciadas con valores que son diferentes a los de la configuración en php.ini o el archivo correspondiente. Esta es una limitación dada por que esos valores automáticos, son aplicados después de que todos los archivos conteniendo parámetros de configuración an sido ejecutados; PERO, esto valores pueden ser cambiados mientras to programa esta ejecutando (esto no hace sentido para todas las directivas, como por ejemplo register_argc_argv).
-
Para facilitar trabajando en la lÃnea de comando, las siguientes constantes son definidas:
constantes especificas de CLI Constant (constante) Description (descripción) STDIN Una stream abierta hacia stdin. Esto nos salva de abrirla con $stdin = fopen('php://stdin', 'r');STDOUT Una stream abierta hacia stdout. Esto nos salva de abrirla con $stdout = fopen('php://stdout', 'w');STDERR Una stream abierta hacia stderr. Esto nos salva de abrirla con $stderr = fopen('php://stderr', 'w');Dado lo anterior, tu no necesitas abrir, como por ejemplo, una stream hacia stderr manualmente, solamente necesitas usar la constante en vez de usar los recursos de la stream:
No necesitas cerrar estas stream explÃcitamente, desde que son cerradas automáticamente por PHP cuando tu programa termina.php -r 'fwrite(STDERR, "stderr\n");' -
El CLI SAPI no cambia el directorio en el cual to estas corrientemente, al directorio donde el programa ejecutado vive!
Ejemplo mostrando la diferencia al CGI SAPI:
<?php
/* Nuestra aplicación llamada.php*/
echo getcwd(), "\n";
?>Cuando usas la versión CGI el resultado es:
Esto claramente muestra que PHP cambia su directorio al usado por el programa que ejecutas.$ pwd /tmp $ php -q otro_directorio/test.php /tmp/otro_directorio
Usando el CLI SAPI resulta:
Esto no da mas flexibilidad cuando escribiendo utilidades en la lÃnea de comando con PHP.$ pwd /tmp $ php -f otro_directorio/test.php /tmp
Note:
Puedes obtener acceso a la lista de opciones proveida por PHP ejecutando PHP con el -hswitch:
Usage: php [options] [-f] <file> [args...] php [options] -r <code> [args...] php [options] [-- args...] -s Display colour syntax highlighted source. -w Display source with stripped comments and whitespace. -f <file> Parse <file>. -v Version number -c <path>|<file> Look for php.ini file in this directory -a Run interactively -d foo[=bar] Define INI entry foo with value 'bar' -e Generate extended information for debugger/profiler -z <file> Load Zend extension <file>. -l Syntax check only (lint) -m Show compiled in modules -i PHP information -r <code> Run PHP <code> without using script tags <?..?> -h This help args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin
Usage: php [options] [-f] <file> [args...] php [options] -r <code> [args...] php [options] [-- args...] -s Display colour syntax highlighted source. (colorear el sintaxis en el código) -w Display source with stripped comments and whitespace. (remueve los comentarios y espacios del código) -f <file> Parse <file>. (analiza <file>) -v Version number (la versión de PHP que estas usando) -c <path>|<file> Look for php.ini file in this directory (usa el php.ini archivo localizado aquí) -a Run interactively (interactivo) -d foo[=bar] Define INI entry foo with value 'bar' (define foo con el valor 'bar' en php.ini) -e Generate extended information for debugger/profiler (genera mas información para el debugger/profiler) -z <file> Load Zend extension <file>. (inicia las exenciones Zend <archive>) -l Syntax check only (lint) (Mira al sintaxis (lint)) -m Show compiled in modules (muestra los módulos compilados) -i PHP information (información PHP) -r <code> Run PHP <code> without using script tags <?..?> (ejecuta PHP <code> sin usar las tags <?..?> en el script -h This help (estas opciones) args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin (Argumentos pasados al programa. Usa -- args cuando el primer argumento empieza con - o tu programa es leído directamente desde stdin)
El CLI SAPI tiene tres diferentes maneras de obtener el código PHP que tu quieres ejecutar:
-
Puedes decir a PHP que ejecute ciertos archivos.
En estos dos ejemplos (aunque utilices el switch -f o no) ejecutan el archivo my_script.php. Tu puedes escoger cualquier archivo para ejecutar - tus programas PHP no tienen que terminar con la exención .php y pueden tener cualquier otra exención tu desees.php my_script.php php -f my_script.php
-
Pasa el código PHP para que sea ejecutado directamente en la lÃnea de comando.
Debes tener cuidado en reguardo a las substituciones variables en tu lÃnea de comando y usando comillas(").php -r 'print_r(get_defined_constants());'
Note: Deves ponerle atención al ejemplo, y notaras que no tiene tags ni al principio ni al final, el comando -r simplemente no las usa. Usando las tags te dará un error cuando trates de ejecutar el programa.
-
Provee el código PHP para ejecutar por medio de stdin
Esto te da la habilidad de dinámicamente crear código PHP y mandarlo al programa, como por ejemplo a continuación:
$ some_application | some_filter | php | sort -u >final_output.txt
Como cualquier aplicación ejecutada en la lÃnea de comando, el PHP binario acepta un numero de argumentos y tu programa también puede recibir argumentos. El numero de argumentos que pueden ser pasados a tu programa no es limitado por PHP (la lÃnea de comando tiene limitaciones en el numero de sÃmbolos que pueden ser pasados; usualmente tu nunca alcanzarÃas este limite). Los argumentos pasados a tu programa, están disponibles en tu array global $argv. El Ãndex cero ("0") siempre contiene el nombre de tu programa (que es - en caso de código que esta viniendo por medio del input estándar, o del switch en la lÃnea de comando -r. La segunda variable global registrada es $argc y contiene el numero de elementos en el array $argv (no el numero de argumentos pasados as programa).
Mientras el argumento que tu quieres pasas a tu programa no comienza con -, no tienes que esperar por nada especial. Pero si el argumento empieza con -, te puede generar problemas, por que PHP pensara que tiene que procesarlo. Para prevenir esto, usa la lista separadora de argumentos: --. Después de que el separador a sido procesado, cada siguiente argumento es pasado sin tocar a tu programa.
# This will not execute the given code but will show the PHP usage # Esto no ejecutara el código pero PHP mostrara el uso $ php -r 'var_dump($argv);' -h Usage: php [options] [-f] <file> [args...] [...] # This will pass the '-h' argument to your script and prevent PHP from showing it's usage # passaremos el argumento '-h' a tu programa y prevenira que PHP demuestre su uso $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" }
Pero, existe otra manera de usar PHP en la lÃnea de comando. Tu puedes escribir un programa donde la primera lÃnea empieza con #!/usr/bin/php (donde /usr/bin/php es la locación de php). Después de esto, tu puedes usar PHP común y corriente. Una vez que tu le as dado permiso de ejecución a tu programa (por ejemplo +x test) tu programa puede ser ejecutado como si fuera digamos un programa en perl:
#!/usr/bin/php
<?php
var_dump($argv);
?>
$ chmod 755 test $ ./test -h -- foo array(4) { [0]=> string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" }
| Opciones | Descripcion |
|---|---|
| -s |
colora el sintaxis de tu código Esta opción usa un mecanismo interno para ejecutar el archivo, y produce una versión coloreada en HML y la escribe como output normal. Nota que todo lo que hace es generar un bloque de <code> [...] </code> HTML tags, no cabecera deHTML es creada.
|
| -w |
Te mostrara tu código sin comentarios ni espacios blancos.
|
| -f |
Ejecuta el archivo indicado en la opción -f. Esta opción es opcional y puede ser excluida. Solamente proveiendo el archivo que necesita ser ejecutado es suficiente. |
| -v |
Escribe la version de PHP, PHP SAPI y Zend al output normal, por ejemplo:
|
| -c |
Con esta opción uno puede especificar el directorio donde encontraremos el php.ini archivo, o tu puedes especificar una versión única del mismo (la cual no tiene que ser llamada php.ini), por ejemplo:
|
| -a |
Corre PHP interactivamente. |
| -d |
Esta opción te hayudara a crear el valor de cualquier directiva de configuración permitidas en el php.ini archivo. El sintaxis es:
Ejemplos:
|
| -e |
Generando mas información para el debugger/profiler. |
| -z |
Activa las extensiones Zend. Si solamente un archivo es dado, PHP tratará de activar estas extensiones directamente desde el directorio predeterminado donde esté la biblioteca en su sistema (Usualmente especificado /etc/ld.so.conf en Linux). Pasando el nombre del archivo con descripción absoluta de la ubicación de sus archivos, no usará las bibliotecas en su sistema. Un archivo conteniendo la información de estos directorios, le dira a PHP que solamente trate de activar las extensiones relativas al directorio donde te encuentras |
| -l |
Esta opción proveerá una forma conveniente para marcar tu sintaxis en tu código. En caso de suceso, el texto "No sintax errors detected in <filename> (no errores de sintaxis fueron detectados) es escrito en tu output normal, y la lÃnea de comando retornara el código 0. En caso de problemas, el texto Errors parsing <filename>, en adición al la forma interna de detectar errores, mensajes son escritos como output normal y tu lÃnea de comando recibirá el código 255 Esta opción no encontrara errores fatales (como por ejemplo funciones indefinida), usa -f si tu quieres probar por esta clase de errores también.
|
| -m |
Usando esta opción, PHP imprime sus módulos internos (y activados) usados por PHP y Zend:
|
| -i | Esta opción llama phpinfo, e imprime los resultado. Si PHP no esta trabajando correctamente, es recomendable que uses esta opción observes si algún mensaje es imprimido antes de, o en medio de la información dada por esta opción. Es un detalle importante que entiendas que el mensaje imprimido es en HTML y por esta razón grandecito. |
| -r |
Esta opción te ayudara a ejecutar PHP directamente desde la lÃnea de comando. Las etiquetas que determinas el principio y al final de tu programa (<?php y ?>) no son necesarias y causaran errores si las pones en tu código.
|
| -h | Con esta opción, tu puedes obtener información acerca de las opciones describÃas anteriormente, y una breve descripción acerca de sus funciones. |
PHP puede ejecutar tus programas absolutamente independiente de tu servidor de páginas de web. Si tu usas Unix, tu puedes añadir una lÃnea especial al principio de tu programa, y hacerlo ejecutable, para que el sistema sepa que programa debe ejecutar tu nueva creación. Si usas windows, tu puedes asociar tu programa con php.exe para que solamente tengas que ejecutarlo como harÃas con otros programas bajo windows, también puedes crear un "batch" archivo para ejecutar tu programa por medio de PHP. La primera lÃnea que usaste para hacer que tu programa funcione en Unix, no le ara daño a tu programa cuando ejecutad bajo windows, pero de esta manera puedes crear programas que puedes ser usados bajo las dos plataformas. A continuación te daremos un ejemplo:
Example #1 Programa para correr en la lÃnea do comando (script.php)
#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
Este es un programa en php entendido para la línea de
comando con una opción.
Usage:
<?php echo $argv[0]; ?> <option>
<option> puede ser cualquier palabra que tu quieras
imprimir. Con la opción --help, -help -h or -?, tu puedes
obtener esta información
<?php
} else {
echo $argv[1];
}
?>
En el programa anterior, usamos una lÃnea especial como nuestra primera lÃnea, para indicar que archivo deber ser ejecutado por PHP. Nosotros trabajamos con una versión de CLI aquÃ, por eso, no tendremos cabeceras de HTTP imprimidas. Hay dos variables que puedes usar cuando escribiendo aplicaciones en la lÃnea de comando en PHP: $argc y $argv. La primera es el numero de argumentos mas uso (el nombre del programa siendo ejecutado). La segunda es un array conteniendo los argumentos, empezando con el programa nombre, y el numero cero "0" ($argv[0]).
En el programa anterior chequeamos si habÃan mas, o menos de dos argumentos. También trata de ver si --help, -help, -h o -?, son llamados, e imprime el mensaje de ayuda.
Si tu quieres ejecutar el programa anterior en Unix, tu tienes que hacerlo ejecutable, y simplemente llamado script.php echo this o script.php -h. En windows, tu puedes hacer un batch archivo para alcanzar estos resultados:
Example #2 Archivo batch para ejecutar el programa php (script.bat)
@c:\php\cli\php.exe script.php %1 %2 %3 %4
Asumiendo que llamaste el programa descrito anteriormente script.php , Y que tienes tu CLI php.exe en c:\php\cli\php.ese este archivo batch, lo ejecutara para ti con las funciones añadidas: script.bat echo this o script.bat -h.
Mira también la documentación de Readline para mas funciones que puedes usar para incrementar tus opciones en este sujeto.
Usando PHP desde la lÃnea de comando
04-Oct-2008 08:27
15-Jun-2008 06:08
Parsing command line: optimization is evil!
One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)
Here is a proposal:
#!/usr/bin/php
<?php
print_r(arguments($argv));
function arguments ( $args )
{
array_shift( $args );
$endofoptions = false;
$ret = array
(
'commands' => array(),
'options' => array(),
'flags' => array(),
'arguments' => array(),
);
while ( $arg = array_shift($args) )
{
// if we have reached end of options,
//we cast all remaining argvs as arguments
if ($endofoptions)
{
$ret['arguments'][] = $arg;
continue;
}
// Is it a command? (prefixed with --)
if ( substr( $arg, 0, 2 ) === '--' )
{
// is it the end of options flag?
if (!isset ($arg[3]))
{
$endofoptions = true;; // end of options;
continue;
}
$value = "";
$com = substr( $arg, 2 );
// is it the syntax '--option=argument'?
if (strpos($com,'='))
list($com,$value) = split("=",$com,2);
// is the option not followed by another option but by arguments
elseif (strpos($args[0],'-') !== 0)
{
while (strpos($args[0],'-') !== 0)
$value .= array_shift($args).' ';
$value = rtrim($value,' ');
}
$ret['options'][$com] = !empty($value) ? $value : true;
continue;
}
// Is it a flag or a serial of flags? (prefixed with -)
if ( substr( $arg, 0, 1 ) === '-' )
{
for ($i = 1; isset($arg[$i]) ; $i++)
$ret['flags'][] = $arg[$i];
continue;
}
// finally, it is not option, nor flag, nor argument
$ret['commands'][] = $arg;
continue;
}
if (!count($ret['options']) && !count($ret['flags']))
{
$ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
$ret['commands'] = array();
}
return $ret;
}
exit (0)
/* vim: set expandtab tabstop=2 shiftwidth=2: */
?>
07-May-2008 04:08
If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there.
versus
Changed CGI install target to php-cgi and 'make install' to install CLI when CGI is selected. (changelog for 5.2.3)
http://www.php.net/ChangeLog-5.php#5.2.3
29-Feb-2008 10:32
When you want to get inputs from STDIN, you may use this function if you like using C coding style.
<?php
// up to 8 variables
function scanf($format, &$a0=NULL, &$a1=NULL, &$a2=NULL, &$a3=NULL,
&$a4=NULL, &$a5=NULL, &$a6=NULL, &$a7=NULL)
{
$num_args = func_num_args();
if($num_args > 1) {
$inputs = fscanf(STDIN, $format);
for($i=0; $i<$num_args-1; $i++) {
$arg = 'a'.$i;
$$arg = $inputs[$i];
}
}
}
scanf("%d", $number);
?>
17-Feb-2008 01:29
I find regex and manually breaking up the arguments instead of havingon $_SERVER['argv'] to do it more flexiable this way.
cli_test.php asdf asdf --help --dest=/var/ -asd -h --option mew arf moo -z
Array
(
[input] => Array
(
[0] => asdf
[1] => asdf
)
[commands] => Array
(
[help] => 1
[dest] => /var/
[option] => mew arf moo
)
[flags] => Array
(
[0] => asd
[1] => h
[2] => z
)
)
<?php
function arguments ( $args )
{
array_shift( $args );
$args = join( $args, ' ' );
preg_match_all('/ (--\w+ (?:[= ] [^-]+ [^\s-] )? ) | (-\w+) | (\w+) /x', $args, $match );
$args = array_shift( $match );
/*
Array
(
[0] => asdf
[1] => asdf
[2] => --help
[3] => --dest=/var/
[4] => -asd
[5] => -h
[6] => --option mew arf moo
[7] => -z
)
*/
$ret = array(
'input' => array(),
'commands' => array(),
'flags' => array()
);
foreach ( $args as $arg ) {
// Is it a command? (prefixed with --)
if ( substr( $arg, 0, 2 ) === '--' ) {
$value = preg_split( '/[= ]/', $arg, 2 );
$com = substr( array_shift($value), 2 );
$value = join($value);
$ret['commands'][$com] = !empty($value) ? $value : true;
continue;
}
// Is it a flag? (prefixed with -)
if ( substr( $arg, 0, 1 ) === '-' ) {
$ret['flags'][] = substr( $arg, 1 );
continue;
}
$ret['input'][] = $arg;
continue;
}
return $ret;
}
print_r( arguments( $argv ) );
?>
12-Feb-2008 10:21
Here's an update to the script a couple of people gave below to read arguments from $argv of the form --name=VALUE and -flag. Changes include:
Don't use $_ARG - $_ is generally considered reserved for the engine.
Don't use regex where a string operation will do just as nicely
Don't overwrite --name=VALUE with -flag when 'name' and 'flag' are the same thing
Allow for VALUE that has an equals sign in it
function arguments($argv) {
$ARG = array();
foreach ($argv as $arg) {
if (strpos($arg, '--') === 0) {
$compspec = explode('=', $arg);
$key = str_replace('--', '', array_shift($compspec));
$value = join('=', $compspec);
$ARG[$key] = $value;
} elseif (strpos($arg, '-') === 0) {
$key = str_replace('-', '', $arg);
if (!isset($ARG[$key])) $ARG[$key] = true;
}
}
return $ARG;
}
29-Oct-2007 07:51
Here's <losbrutos at free dot fr> function modified to support unix like param syntax like <B Crawford> mentions:
<?php
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches)) {
$key = $matches[1];
switch ($matches[2]) {
case '':
case 'true':
$arg = true;
break;
case 'false':
$arg = false;
break;
default:
$arg = $matches[2];
}
/* make unix like -afd == -a -f -d */
if(preg_match("/^-([a-zA-Z0-9]+)/", $matches[0], $match)) {
$string = $match[1];
for($i=0; strlen($string) > $i; $i++) {
$_ARG[$string[$i]] = true;
}
} else {
$_ARG[$key] = $arg;
}
} else {
$_ARG['input'][] = $arg;
}
}
return $_ARG;
}
?>
Sample:
eromero@ditto ~/workspace/snipplets $ foxogg2mp3.php asdf asdf --help --dest=/var/ -asd -h
Array
(
[input] => Array
(
[0] => /usr/local/bin/foxogg2mp3.php
[1] => asdf
[2] => asdf
)
[help] => 1
[dest] => /var/
[a] => 1
[s] => 1
[d] => 1
[h] => 1
)
23-Oct-2007 05:11
I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:
#!/usr/bin/php -q
<?php
function inKey($vals) {
$inKey = "";
While(!in_array($inKey,$vals)) {
$inKey = trim(`read -s -n1 valu;echo \$valu`);
}
return $inKey;
}
function echoAT($Row,$Col,$prompt="") {
// Display prompt at specific screen coords
echo "\033[".$Row.";".$Col."H".$prompt;
}
// Display prompt at position 10,10
echoAT(10,10,"Opt : ");
// Define acceptable responses
$options = array("1","2","3","4","X");
// Get user response
$key = inKey($options);
// Display user response & exit
echoAT(12,10,"Pressed : $key\n");
?>
Hope this helps someone.
22-Oct-2007 10:01
I have not seen in this thread any code snippets that support the full *nix style argument parsing. Consider this:
<?php
print_r(getArgs($_SERVER['argv']));
function getArgs($args) {
$out = array();
$last_arg = null;
for($i = 1, $il = sizeof($args); $i < $il; $i++) {
if( (bool)preg_match("/^--(.+)/", $args[$i], $match) ) {
$parts = explode("=", $match[1]);
$key = preg_replace("/[^a-z0-9]+/", "", $parts[0]);
if(isset($parts[1])) {
$out[$key] = $parts[1];
}
else {
$out[$key] = true;
}
$last_arg = $key;
}
else if( (bool)preg_match("/^-([a-zA-Z0-9]+)/", $args[$i], $match) ) {
for( $j = 0, $jl = strlen($match[1]); $j < $jl; $j++ ) {
$key = $match[1]{$j};
$out[$key] = true;
}
$last_arg = $key;
}
else if($last_arg !== null) {
$out[$last_arg] = $args[$i];
}
}
return $out;
}
/*
php file.php --foo=bar -abc -AB 'hello world' --baz
produces:
Array
(
[foo] => bar
[a] => true
[b] => true
[c] => true
[A] => true
[B] => hello world
[baz] => true
)
*/
?>
27-Sep-2007 08:54
an another "another variant" :
<?php
function arguments($argv)
{
$_ARG = array();
foreach ($argv as $arg)
{
if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
{
$key = $matches[1];
switch ($matches[2])
{
case '':
case 'true':
$arg = true;
break;
case 'false':
$arg = false;
break;
default:
$arg = $matches[2];
}
$_ARG[$key] = $arg;
}
else
{
$_ARG['input'][] = $arg;
}
}
return $_ARG;
}
?>
$php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false
Array
(
[input] => Array
(
[0] => myscript.php
[1] => arg1
)
[arg2] => val2
[arg3] => arg3
[arg4] => true
[arg5] => true
[arg5] => false
)
17-Aug-2007 03:24
For those who was unable to clear the windows screen trying to run CLS command:
CLS is not an windows executable file! It is an option from command.com!
So, the rigth command is
system("command /C cls");
23-Jul-2007 02:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
$_ARG[$reg[1]] = $reg[2];
} elseif(ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
$_ARG[$reg[1]] = 'true';
} else {
$_ARG['input'][]=$arg;
}
}
return $_ARG;
}
$ php myscript.php --user=nobody /etc/apache2/*
Array
(
[input] => Array
(
[0] => myscript.php
[1] => /etc/apache2/apache2.conf
[2] => /etc/apache2/conf.d
[3] => /etc/apache2/envvars
[4] => /etc/apache2/httpd.conf
[5] => /etc/apache2/mods-available
[6] => /etc/apache2/mods-enabled
[7] => /etc/apache2/ports.conf
[8] => /etc/apache2/sites-available
[9] => /etc/apache2/sites-enabled
)
[user] => nobody
)
26-Jun-2007 02:02
In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
04-Jun-2007 08:16
Just a variant of previous script to accept arguments with '=' also
<?php
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
$_ARG[$reg[1]] = $reg[2];
} elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
$_ARG[$reg[1]] = 'true';
}
}
return $_ARG;
}
?>
$ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456"
Array
(
[user] => nobody
[password] => secret
[p] => true
[access] => host=127.0.0.1 port=456
)
13-May-2007 05:55
While working with command line scripts it is tedious to handle the arguments in a numerated array.
The following code will:
If the argument is of the form –NAME=VALUE it will be represented in the array as an element with the key NAME and the value VALUE. I the argument is a flag of the form -NAME it will be represented as a boolean with the name NAME with a value of true in the associative array.
<?php
function arguments($argv) {
$_ARG = array();
foreach ($argv as $arg) {
if (ereg('--[a-zA-Z0-9]*=.*',$arg)) {
$str = split("=",$arg); $arg = '';
$key = ereg_replace("--",'',$str[0]);
for ( $i = 1; $i < count($str); $i++ ) {
$arg .= $str[$i];
}
$_ARG[$key] = $arg;
} elseif(ereg('-[a-zA-Z0-9]',$arg)) {
$arg = ereg_replace("-",'',$arg);
$_ARG[$arg] = 'true';
}
}
return $_ARG;
}
?>
Example:
<?php print_r(arguments($argv)); ?>
# php5 myscript.php --user=nobody --password=secret -p
Array
(
[user] => nobody
[password] => secret
[p] => true
)
09-Apr-2007 06:27
I had a problem with PHP 5.2.0 (cli) (winXP) that no output was printed when I tried to run any file. Using the -n switch solved the problem.
Apparently the interpreter can't always find php.ini, even though both exist in the same folder and the PATH variable is set correctly. No error messages were printed either.
24-Mar-2007 03:48
i use emacs in c-mode for editing. in 4.3, starting a cli script like so:
#!/usr/bin/php -q /* -*- c -*- */
<?php
told emacs to drop into c-mode automatically when i loaded the file for editing. the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.
in 5.2, '-q' has apparently been deprecated. replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:
#!/usr/bin/php -- /* -*- c -*- */
<?php
don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
09-Mar-2007 11:14
To display colored text when it is actually supported :
<?php
echo "\033[31m".$myvar; // red foreground
echo "\033[41m".$myvar; // red background
?>
To reset these settings :
<?php
echo "\033[0m";
?>
More fun :
<?php
echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
?>
More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
06-Mar-2007 12:03
python coders might miss this construct when working in PHP:
if __name__=='__main__':
# handle direct invocation from command line
it's a great way to embed little bits of test code (or a full-on cli for that matter),
while keeping the source file usable in other contexts.
Far as I can tell, this is the closest approximation available in PHP5:
if ('cli'===php_sapi_name() &&
__FILE__===realpath(
getcwd().DIRECTORY_SEPARATOR.$_SERVER['argv'][0]
)) {
// handle direct invocation from command line
}
27-Nov-2006 12:46
Hi,
This function clears the screen, like "clear screen"
<?php
function clearscreen($out = TRUE) {
$clearscreen = chr(27)."[H".chr(27)."[2J";
if ($out) print $clearscreen;
else return $clearscreen;
}
?>
14-Nov-2006 04:57
An addition to my previous post (you can replace it)
If your php script doesn't run with shebang (#!/usr/bin/php),
and it issues the beautifull and informative error message:
"Command not found." just dos2unix yourscript.php
et voila.
If you still get the "Command not found."
Just try to run it as ./myscript.php , with the "./"
if it works - it means your current directory is not in the executable search path.
If your php script doesn't run with shebang (#/usr/bin/php),
and it issues the beautifull and informative message:
"Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.
\Alon
It seems like 'max_execution_time' doesn't work on CLI.
<?php
php -d max_execution_time=20
-r '$foo = ini_get("max_execution_time"); var_dump($foo);'
?>
will print string(2) "20", but if you'l run infinity while: while(true) for example, it wouldn't stop after 20 seconds.
Testes on Linux Gentoo, PHP 5.1.6.
16-Sep-2006 06:59
On windows, you can simulate a cls by echoing out just \r. This will keep the cursor on the same line and overwrite what was on the line.
for example:
<?php
echo "Starting Iteration" . "\n\r";
for ($i=0;$i<10000;$i++) {
echo "\r" . $i;
}
echo "Ending Iteration" . "\n\r";
?>
21-Aug-2006 03:20
If your php script doesn't run with shebang (#!/usr/bin/php),
and it issues the beautifull and informative error message:
"Command not found." just dos2unix yourscript.php
et voila.
If your php script doesn't run with shebang (#/usr/bin/php),
and it issues the beautifull and informative message:
"Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.
\Alon
22-Feb-2006 02:27
Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).
To do this in C++:
// We will run php.exe as a child process after creating
// two pipes and attaching them to stdin and stdout
// of the child process
// Define sa struct such that child inherits our handles
SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
// Create the handles for our two pipes (two handles per pipe, one for each end)
// We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;
// Now create the pipes, and make them inheritable
CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);
// Now we have two pipes, we can create the process
// First, fill out the usage structs
STARTUPINFO si = { sizeof(STARTUPINFO) };
PROCESS_INFORMATION pi;
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdOutput = hStdoutWr;
si.hStdInput = hStdinRd;
// And finally, create the process
CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
// Close the handles we aren't using
CloseHandle(hStdoutWr);
CloseHandle(hStdinRd);
// Now that we have the process running, we can start pushing PHP at it
WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);
// When we're done writing to stdin, we close that pipe
CloseHandle(hStdinWr);
// Reading from stdout is only slightly more complicated
int i;
std::string processed("");
char buf[128];
while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
for (i = 0; i < dwRead; i++)
processed += buf[i];
}
// Done reading, so close this handle too
CloseHandle(hStdoutRd);
A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
25-Sep-2005 03:08
When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:
UNIX:
cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
DOS/Windows:
type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
20-Sep-2005 03:27
I needed this, you proly wont tho.
puts the exicution args into $_GET
<?php
if ($argv) {
foreach ($argv as $k=>$v)
{
if ($k==0) continue;
$it = explode("=",$argv[$i]);
if (isset($it[1])) $_GET[$it[0]] = $it[1];
}
}
?>
17-Sep-2005 12:06
To pass more than 9 arguments to your php-script on Windows, you can use the 'shift'-command in a batch file. After using 'shift', %1 becomes %0, %2 becomes %1 and so on - so you can fetch argument 10 etc.
Here's an example - hopefully ready-to-use - batch file:
foo.bat:
---------
@echo off
:init_arg
set args=
:get_arg
shift
if "%0"=="" goto :finish_arg
set args=%args% %0
goto :get_arg
:finish_arg
set php=C:\path\to\php.exe
set ini=C:\path\to\php.ini
%php% -c %ini% foo.php %args%
---------
Usage on commandline:
foo -1 -2 -3 -4 -5 -6 -7 -8 -9 -foo -bar
A print_r($argv) will give you all of the passed arguments.
18-Aug-2005 04:53
Hi, parsing the commandline (argv) can be very simple in PHP.
If you use keyword parms like:
script.php parm1=value parm3=value
All you have to do in script.php is:
for ($i=1; $i < $argc; $i++) {parse_str($argv[$i]);}
$startup=compact('parm1', 'parm2', 'parm3');
14-Jul-2005 08:44
dunno if this is on linux the same but on windows evertime
you send somthing to the console screen php is waiting for
the console to return. therefor if you send a lot of small
short amounts of text, the console is starting to be using
more cpu-cycles then php and thus slowing the script.
take a look at this sheme:
cpu-cycle:1 ->php: print("a");
cpu-cycle:2 ->cmd: output("a");
cpu-cycle:3 ->php: print("b");
cpu-cycle:4 ->cmd: output("b");
cpu-cycle:5 ->php: print("c");
cpu-cycle:6 ->cmd: output("c");
cpu-cylce:7 ->php: print("d");
cpu-cycle:8 ->cmd: output("d");
cpu-cylce:9 ->php: print("e");
cpu-cycle:0 ->cmd: output("e");
on the screen just appears "abcde". but if you write
your script this way it will be far more faster:
cpu-cycle:1 ->php: ob_start();
cpu-cycle:2 ->php: print("abc");
cpu-cycle:3 ->php: print("de");
cpu-cycle:4 ->php: $data = ob_get_contents();
cpu-cycle:5 ->php: ob_end_clean();
cpu-cycle:6 ->php: print($data);
cpu-cycle:7 ->cmd: output("abcde");
now this is just a small example but if you are writing an
app that is outputting a lot to the console, i.e. a text
based screen with frequent updates, then its much better
to first cach all output, and output is as one big chunk of
text instead of one char a the time.
ouput buffering is ideal for this. in my script i outputted
almost 4000chars of info and just by caching it first, it
speeded up by almost 400% and dropped cpu-usage.
because what is being displayed doesn't matter, be it 2
chars or 40.0000 chars, just the call to output takes a
great deal of time. remeber that.
maybe someone can test if this is the same on unix-based
systems. it seems that the STDOUT stream just waits for
the console to report ready, before continueing execution.
24-Jun-2005 11:07
For windows clearing the screen using "system('cls');" does not work (at least for me)...
Although this is not pretty it works... Simply send 24 newlines after the output (for one line of output, 23 for two, etc
Here is a sample function and usage:
function CLS($lines){ // $lines = number of lines of output to keep
for($i=24;$i>=$lines;$i--) @$return.="\n";
return $return;
}
fwrite(STDOUT,"Still Processing: Total Time ".$i." Minutes so far..." . CLS(1));
Hope This Helps,
Wallacebw
30-May-2005 10:32
If you are using Windows XP (I think this works on 2000, too) and you want to be able to right-click a .php file and run it from the command line, follow these steps:
1. Run regedit.exe and *back up the registry.*
2. Open HKEY_CLASSES_ROOT and find the ".php" key.
IF IT EXISTS:
------------------
3. Look at the "(Default)" value inside it and find the key in HKEY_CLASSES_ROOT with that name.
4. Open the "shell" key inside that key. Skip to 8.
IF IT DOESN'T:
------------------
5. Add a ".php" key and set the "(Default)" value inside it to something like "phpscriptfile".
6. Create another key in HKEY_CLASSES_ROOT called "phpscriptfile" or whatever you chose.
7. Create a key inside that one called "shell".
8. Create a key inside that one called "run".
9. Set the "(Default)" value inside "run" to whatever you want the menu option to be (e.g. "Run").
10. Create a key inside "run" called "command".
11. Set the "(Default)" value inside "command" to:
cmd.exe /k C:\php\php.exe "%1"
Make sure the path to PHP is appropriate for your installation. Why not just run it with php.exe directly? Because you (presumably) want the console window to remain open after the script ends.
You don't need to set up a webserver for this to work. I downloaded PHP just so I could run scripts on my computer. Hope this is useful!
27-May-2005 04:52
One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.
I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).
I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".
Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New' and typing php3 in the window that pops up.
Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.
You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed
Hope this is useful to somebody
03-May-2005 11:29
#!/usr/bin/php -q
<?
/**********************************************
* Simple argv[] parser for CLI scripts
* Diego Mendes Rodrigues - São Paulo - Brazil
* diego.m.rodrigues [at] gmail [dot] com
* May/2005
**********************************************/
class arg_parser {
var $argc;
var $argv;
var $parsed;
var $force_this;
function arg_parser($force_this="") {
global $argc, $argv;
$this->argc = $argc;
$this->argv = $argv;
$this->parsed = array();
array_push($this->parsed,
array($this->argv[0]) );
if ( !empty($force_this) )
if ( is_array($force_this) )
$this->force_this = $force_this;
//Sending parameters to $parsed
if ( $this->argc > 1 ) {
for($i=1 ; $i< $this->argc ; $i++) {
//We only have passed -xxxx
if ( substr($this->argv[$i],0,1) == "-" ) {
//Se temos -xxxx xxxx
if ( $this->argc > ($i+1) ) {
if ( substr($this->argv[$i+1],0,1) != "-" ) {
array_push($this->parsed,
array($this->argv[$i],
$this->argv[$i+1]) );
$i++;
continue;