downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

Référence des fonctions> <Fonctions désactivées par le Safe Mode
Last updated: Fri, 14 Aug 2009

view this page in

Utiliser PHP en ligne de commande

Depuis la version 4.3.0, PHP supporte un nouveau type de SAPI (Server Application Programming Interface, c'est-à-dire Interface de Programmation d'Applications Serveur) appelé CLI, ce qui signifie Command Line Interface et se traduit par "Interface de Ligne de Commande". Comme son nom l'indique, ce type SAPI cible les applications Shell (ou desktop), écrites en PHP. Il y a un certain nombre de différences entre le type CLI SAPI et les autres SAPI expliqués dans ce chapitre. Il convient de préciser que CLI et CGI sont des SAPI différentes, bien qu'ils partagent des comportements similaires.

Le CLI SAPI a été publié pour la première fois avec la version PHP 4.2.0, mais il était expérimental, et devait être explicitement activé avec l'option --enable-cli lorsque vous exécutez le script ./configure. Depuis PHP 4.3.0, le CLI SAPI n'est plus expérimental, et l'option --enable-cli est activée par défaut. Vous pouvez utiliser l'option --disable-cli pour le désactiver.

Depuis PHP 4.3.0, le nom, l'emplacement et l'existence des binaires CLI/CGI vont dépendre de la façon dont PHP est installé sur votre système. Par défaut, en exécutant make, les deux binaires CGI et CLI sont compilés et nommés respectivement sapi/cgi/php et sapi/cli/php dans votre répertoire source PHP. Vous remarquerez que les deux se nomment php. Ce qui se passe ensuite pendant le make install dépend de votre ligne de configuration. Si un module SAPI, apxs par exemple, a été choisi pendant la configuration, ou que l'option --disable-cgi a été activée, le CLI est copié dans {PREFIX}/bin/php pendant le make install. Si, par exemple, --with--apxs figure dans votre ligne de configuration, le CLI est copié dans {PREFIX}/bin/php pendant le make install, sinon c'est le CGI qui y est placé. Si vous voulez forcer l'installation du binaire CGI, lancez make install-cli après le make install. Sinon, vous pouvez aussi spécifier --disable-cgi dans votre ligne de configuration.

Note: Du fait que les deux options --enable-cli et --enable-cgi sont activées par défaut, avoir simplement --enable-cli dans votre ligne de configuration n'implique pas nécessairement que le CLI soit renommé en {PREFIX}/bin/php pendant le make install.

Les paquets Windows entre PHP 4.2.0 et PHP 4.2.3 installaient le CLI en tant que php-cli.exe et laissaient le CGI en tant que php-cli.exe dans le même répertoire. Depuis PHP 4.3.0, le paquet Windows installe le CLI en tant que php.exe dans un répertoire à part nommé cli, donc cli/php.exe. Depuis PHP 5, le CLI est installé dans le répertoire principal en tant que php.exe. La version CGI est nommée quand à elle php-cgi.exe.

Depuis PHP 5, un nouveau fichier php-win.exe est installé. C'est l'équivalent de la version CLI à ceci près qu'il n'affiche rien et ainsi ne fait pas apparaître de console (aucune fenêtre "dos" n'apparaît à l'écran). Ce comportement est similaire à celui de php-gtk. Vous pouvez l'activer avec l'option --enable-cli-win32.

Note: Quel SAPI est installé ?
À partir d'un terminal, lancer php -v vous dira si php est en version CGI ou CLI. Vous pouvez aussi consulter la fonction php_sapi_name() et la constante PHP_SAPI.

Note: Une page man de manuel Unix a été ajoutée avec PHP 4.3.2. Vous pouvez la consulter en tapant man php dans votre interpréteur de commande.

Les différences les plus notables entre le CLI SAPI et les SAPI sont :

  • Contrairement au CGI SAPI, aucun en-tête HTTP n'est écrit dans le résultat.

    Bien que le CGI SAPI fournisse un moyen de supprimer les en-têtes HTTP, il n'y a pas moyen d'activer les en-têtes HTTP dans le CLI SAPI.

    CLI est lancé en mode silencieux par défaut, bien que les options -q et --no-header soient gardées pour rester compatible avec les anciennes versions CGI.

    Il ne change pas le répertoire courant en celui du script. (les options -C et --no-chdir sont gardées par souci de compatibilité)

    Messages d'erreurs en texte brut (pas de formatage HTML).

  • Il y a plusieurs directives du php.ini qui sont ignorées par le CLI SAPI, car elles n'ont pas de sens en environnement shell :

    Directives php.ini ignorées
    Directive Valeur par défaut pour CLI SAPI Commentaire
    html_errors FALSE Il peut être bien difficile de lire les messages d'erreur sur un terminal lorsqu'ils sont noyés dans des balises HTML sans grand intérêt. Par conséquent, cette directive est forcée à FALSE.
    implicit_flush TRUE Il est souhaitable que tout affichage en provenance de print(), echo() et consorts, soit immédiatement affiché dans le terminal, et non pas placé dans un buffer quelconque. Vous pouvez toujours utiliser la bufferisation de sortie si vous voulez retarder un affichage, ou bien en manipuler le contenu une dernière fois.
    max_execution_time 0 (sans limite) Étant données les possibilités infinies de PHP en environnement shell, le temps d'exécution maximal d'un script PHP a été rendu illimité. Alors que les scripts destinés au web doivent s'accomplir en une fraction de seconde, il arrive que les scripts shell requièrent bien plus de temps.
    register_argc_argv TRUE

    En donnant la valeur de TRUE à cette directive, vous aurez toujours accès à la variable argc (représentant le nombre d'arguments passés à l'application) et argv (le tableau contenant les arguments passés) dans le CLI SAPI.

    Depuis PHP 4.3.0, les variables $argc et $argv sont définies et remplies avec les valeurs appropriées, en utilisant CLI SAPI. Avant cette version, la création de ces variables était liée au comportement des versions CGI et MODULE, qui requièrent l'activation de la directive register_globals. Indépendamment de la version ou de la valeur de register_globals, vous pouvez toujours accéder à $_SERVER et $HTTP_SERVER_VARS. Par exemple : $_SERVER['argv']

    Note: Ces directives ne peuvent pas être initialisées avec d'autres valeurs dans le fichier php.ini ou par une autre méthode. C'est une limitation, car ces valeurs par défaut s'appliquent une fois que tous les autres fichiers de configuration ont été analysés. Cependant, ces valeurs peuvent être modifiées durant l'exécution (ce qui n'est pas logique pour certaines directives, comme register_argc_argv).

  • Pour faciliter le travail en environnement shell, les constantes suivantes sont définies :

    Constantes spécifiques au CLI
    Constante Description
    STDIN

    Un pointeur de fichier déjà disponible vers stdin. Cela évite de l'ouvrir avec

    <?php

    $stdin 
    fopen('php://stdin''r');

    ?>

    Si vous voulez lire une seule ligne depuis stdin, vous pouvez utiliser :

    <?php
    $line 
    trim(fgets(STDIN)); // lit une seule ligne depuis STDIN
    fscanf(STDIN"%d\n"$number); // lit les nombres depuis STDIN
    ?>

    STDOUT

    Un descripteur de fichier déjà disponible vers stdout. Cela évite de l'ouvrir avec

    <?php

    $stdout 
    fopen('php://stdout''w');

    ?>

    STDERR

    Un descripteur de fichier déjà disponible vers stderr. Cela évite de l'ouvrir avec

    <?php

    $stderr 
    fopen('php://stderr''w');

    ?>

    Étant donné ce qui précède, vous n'avez pas besoin d'ouvrir un flux vers stderr par vous-même, mais vous pouvez utiliser cette constante directement, comme un descripteur de fichier :

    php -r 'fwrite(STDERR, "stderr\n");'

    Vous n'avez pas non plus à fermer explicitement ces fichiers, PHP s'en chargera automatiquement à la fin du script.

    Note: Ces constantes ne sont pas disponibles si le script PHP est lu depuis stdin.

  • Le CLI SAPI ne transforme pas le dossier courant en dossier d'exécution du script !

    Exemple montrant la différence avec le CGI SAPI :

    <?php
    // Un test simple : affiche le dossier d'exécution */
    echo getcwd(), "\n";
    ?>

    Lorsque vous utilisez la version CGI, l'affichage sera :

    $ pwd
    /tmp
    
    $ php-cgi -f autre_dossier/test.php
    /tmp/autre_dossier
    

    Cela montre clairement que PHP modifie le dossier courant, et utilise le dossier du script exécuté.

    En utilisant le CLI SAPI, on obtient :

    $ pwd
    /tmp
    
    $ php -f autre_dossier/test.php
    /tmp
    

    Cela donne beaucoup plus de souplesse lorsque vous rédigez des scripts shell avec PHP.

    Note: Le CGI SAPI se comporte de la même façon que le CLI SAPI, en lui passant l'option -C, lorsque vous l'invoquez en ligne de commande.

La liste des options de ligne de commande fournies par PHP est disponible à n'importe quel moment en exécutant PHP avec l'option -h :

Usage: php [options] [-f] <file> [--] [args...]
 php [options] -r <code> [--] [args...]
 php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
 php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
 php [options] -- [args...]
 php [options] -a

-a               Run interactively
-c <path>|<file> Look for php.ini file in this directory
-n               No php.ini file will be used
-d foo[=bar]     Define INI entry foo with value 'bar'
-e               Generate extended information for debugger/profiler
-f <file>        Parse and execute <file>.
-h               This help
-i               PHP information
-l               Syntax check only (lint)
-m               Show compiled in modules
-r <code>        Run PHP <code> without using script tags <?..?>
-B <begin_code>  Run PHP <begin_code> before processing input lines
-R <code>        Run PHP <code> for every input line
-F <file>        Parse and execute <file> for every input line
-E <end_code>    Run PHP <end_code> after processing all input lines
-H               Hide any passed arguments from external tools.
-s               Display colour syntax highlighted source.
-v               Version number
-w               Display source with stripped comments and whitespace.
-z <file>        Load Zend extension <file>.

args...          Arguments passed to script. Use -- args when first argument
                 starts with - or script is read from stdin

--ini            Show configuration file names

--rf <name>      Show information about function <name>.
--rc <name>      Show information about class <name>.
--re <name>      Show information about extension <name>.
--ri <name>      Show configuration for extension <name>.

Le CLI SAPI dispose de trois moyens pour lire le code du script PHP que vous voulez exécuter :

  1. Indiquer à PHP d'exécuter un fichier donné :

    php mon_script.php
    
    php -f mon_script.php
    

    Les deux méthodes (en utilisant -f ou pas) exécutent le script contenu dans le fichier mon_script.php. Vous pouvez choisir n'importe quel fichier, et ces fichiers ne sont pas tenus d'utiliser l'extension .php. N'importe quelle extension peut faire l'affaire.

    Note: Si vous devez passer des arguments à votre script, vous devez passer -- comme premier argument lorsque vous utilisez -f.

  2. Donner du code PHP à exécuter directement en ligne de commande.

    php -r 'print_r(get_defined_constants());'
    

    Une attention particulière doit alors être apportée aux variables d'environnement, qui seront remplacées, et aux guillemets, qui ont des significations spéciales en ligne de commande.

    Note: Lisez l'exemple attentivement, il n'y a ni balise d'ouverture, ni balise de fermeture ! L'option -r rend caduque l'utilisation de celles-ci, et les ajouter conduirait alors à une erreur d'analyse syntaxique.

  3. Alimenter l'entrée standard en code PHP (stdin).

    Cela donne la possibilité de créer dynamiquement du code PHP, puis de le fournir à PHP, et enfin, de le traiter à nouveau en shell. Voici un exemple fictif :

    $ some_application | some_filter | php | sort -u >final_output.txt
    

Il n'est pas possible de combiner ces trois modes d'exécution.

Comme toute application shell, l'exécutable PHP accepte des arguments, et votre script PHP peut aussi les recevoir. Le nombre d'arguments n'est pas limité par PHP (le shell a une limite en terme de nombre de caractères qui peuvent être passés. Généralement, vous n'atteindrez pas cette limite). Les arguments passés au script seront transmis via la variable tableau $argv. L'index zéro contiendra toujours le nom du script appelé (qui sera - dans le cas où le code PHP arrive de l'entrée standard ou depuis la ligne de commande, passé -r). L'autre variable globale fournie est $argc qui contient le nombre d'éléments dans le tableau $argv (ce nombre est différent du nombre d'arguments passés au script).

Tant que les arguments que vous passez à votre script ne commencent pas par le caractère -, il n'y a rien de spécial à surveiller. Si vous passez des arguments à votre script qui commencent par -, cela posera des problèmes car PHP va penser qu'il doit les interpréter. Pour éviter cela, utilisez le séparateur --. Après cet argument, tous les arguments suivants seront passés à votre script sans être modifiés ou analysés par PHP.

# Cela ne va pas exécuter le code, mais afficher l'aide de PHP
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]

# Cela va passer l'argument '-h' à votre script, et éviter que PHP ne le traite
$ php -r 'var_dump($argv);' -- -h
array(2) {
[0]=>
string(1) "-"
[1]=>
string(2) "-h"
}

Cependant, il y a une autre méthode pour utiliser PHP en script shell. Vous pouvez aussi utiliser la ligne #!/usr/bin/php en tout début de votre script, suivie de code PHP compris entre balise ouvrantes/fermantes. Après avoir mis les droits d'exécution sur votre script (chmod +x test), il peut être exécuté comme un script shell ou perl habituel :

Exemple #1 Exécute un script PHP en tant que script shell

<?php
var_dump
($argv);
?>

En supposant que ce fichier s'appelle test, dans le dossier courant, nous pouvons alors faire ceci :

$ chmod +x test
$ ./test -h -- foo
array(4) {
   [0]=>
   string(6) "./test"
   [1]=>
   string(2) "-h"
   [2]=>
   string(2) "--"
   [3]=>
   string(3) "foo"
}

Comme vous le voyez, aucune précaution n'est nécessaire pour passer des paramètres qui commencent par - à votre script.

Les options longues sont disponibles depuis PHP 4.3.3.

Options de ligne de commande
Option Option longue Description
-a --interactive

Lance PHP de façon interactive. Si vous compilez PHP avec l'extension Readline (qui n'est pas disponible sous Windows), vous aurez un shell joli, incluant la fonctionnalité de complétion (e.g. vous pouvez commencer à taper un nom de variable, taper la touche TABULATION et PHP complètera son nom) et un historique de ce que vous entrez au clavier qui peut être consulté en utilisant les touches fléchées. Cet historique est sauvegardé dans le fichier ~/.php_history.

Note: Les fichiers incluent dans auto_prepend_file et auto_append_file sont analysés dans ce mode avec quelques restrictions - par exemple, les fonctions doivent être définies avant d'être appelées.

Note: Autoloading n'est pas disponible si vous utilisez PHP en mode intéractif CLI.

-c --php-ini

Cette option permet de spécifier le nom du dossier dans lequel se trouve le fichier php.ini, ou encore de spécifier un fichier de configuration (INI) directement (qui ne s'appelle pas obligatoirement php.ini) :

$ php -c /custom/directory/ mon_script.php

$ php -c /custom/directory/custom-file.ini mon_script.php

Si vous ne spécifiez pas cette option, le fichier est recherché dans les endroits par défaut.

-n --no-php-ini

Ignore complètement php.ini. Cette option est disponible depuis PHP 4.3.0.

-d --define

Cette option permet de modifier n'importe quelle directive de configuration du fichier php.ini. La syntaxe est :

 -d configuration_directive[=value]

Exemples :

# L'omission de la valeur conduit à donner la valeur de "1"
$ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(1) "1"

# Passer une valeur vide conduit à donner la valeur de ""
php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(0) ""

# La directive de configuration sera n'importe quelle valeur passée après le caractère '='
$  php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(2) "20"
$  php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
string(15) "doesntmakesense"

-e --profile-info

Génère des informations étendues pour le profilage et le débogage.

-f --file

Analyse et exécute le fichier donné après l'option -f. Cette option est facultative, et peut être omise. Le seul nom du fichier est suffisant.

Note: Pour passer des arguments à votre script, le premier argument doit être --, sinon, PHP les interprètera comme des options PHP.

-h et -? --help Avec cette option, vous pouvez obtenir des informations sur la liste courante des options de la ligne de commande, ainsi que leur description.
-i --info Cette option appelle la fonction phpinfo(), et affiche le résultat. Si PHP ne fonctionne pas correctement, il est recommandé d'utiliser la commande php -i et de voir s'il n'y a pas d'erreurs affichées avant ou après la table d'information. N'oubliez pas que le résultat de cette option, si vous utilisez le mode CGI, est au format HTML, et donc de taille conséquente.
-l --syntax-check

Cette option permet de faire une vérification syntaxique sur le code PHP fourni. En cas de réussite, le message No syntax errors detected in <filename> (Littéralement, aucune erreur de syntaxe n'a été détectée dans le fichier) est affiché sur la sortie standard, et le script shell retourne 0. En cas d'erreur, le message Errors parsing <filename> (Littéralement, erreur d'analyse dans le fichier filename) est affiché, en plus des messages d'erreurs détectés par l'analyseur lui-même. Le script Shell retourne le code -1.

Cette option ne détecte pas les erreurs fatales (par exemple les fonctions non définies). Utilisez -f si vous voulez tester aussi ces erreurs.

Note: Cette option ne fonctionne pas avec l'option -r.

-m --modules

Cette option liste les extensions PHP et Zend compilées (et chargées) :

$ php -m
[PHP Modules]
xml
tokenizer
standard
session
posix
pcre
overload
mysql
mbstring
ctype

[Zend Modules]

-r --run

Cette option permet l'exécution de PHP directement dans la ligne de commande. Les balises de PHP (<?php et ?>) ne sont pas nécessaires, et causeront une erreur d'analyse si elles sont présentes.

Note: Une attention toute particulière doit être portée lors de l'utilisation de cette option de PHP, pour qu'il n'y ait pas de collision avec les substitutions de variables en ligne de commande, réalisées par le shell.

Exemple conduisant à une erreur d'analyse :

$ php -r "$foo = get_defined_constants();"
Command line code(1) : Parse error - parse error, unexpected '='

Le problème ici est que le shell (sh/bash) effectue une substitution de variables, même avec les guillemets doubles ". puisque la variable $foo n'est probablement pas définie dans le shell, elle est remplacée par rien, ce qui fait que le code passé à PHP pour l'exécution est :

$ php -r " = get_defined_constants();"

La solution de ce problème est d'utiliser les guillemets simples '. Les variables de ces chaînes ne seront pas substituées par leurs valeurs par le shell.

$ php -r '$foo = get_defined_constants(); var_dump($foo);'
array(370) {
["E_ERROR"]=>
int(1)
["E_WARNING"]=>
int(2)
["E_PARSE"]=>
int(4)
["E_NOTICE"]=>
int(8)
["E_CORE_ERROR"]=>
[...]

Si vous utilisez un shell différent de sh/bash, vous pouvez rencontrer d'autres problèmes. N'hésitez pas à ouvrir un rapport de bogues à » http://bugs.php.net/. Il est toujours très facile d'avoir des problèmes lorsque vous essayez d'inclure des variables shell dans le code, ou d'utiliser les antislash pour la protection. Vous aurez été prévenu.

Note: -r est disponible avec le CLI SAPI et pas avec le CGI SAPI.

Note: Cette option est utilisée pour des choses vraiment de base. Ainsi, quelques directives de configuration (par exemple auto_prepend_file et auto_append_file) sont ignorées dans ce mode.

-B --process-begin

PHP code à exécuter avant le traitement de stdin. Ajouté en PHP 5.

-R --process-code

Code PHP à exécuter pour chaque ligne en entrée. Ajouté en PHP 5.

Il y a deux variables spéciales de disponibles dans ce mode : $argn et $argi. $argn doit contenir la ligne PHP traitée à ce moment donné, tandis que $argi doit contenir le numéro de la ligne.

-F --process-file

Fichier PHP à exécuter pour chaque ligne en entrée. Ajouté en PHP 5.

-E --process-end

Code PHP à exécuter après avoir effectué l'entrée. Ajouté en PHP 5.

Exemple #2 Exemple d'utilisation des options -B, -R et -E pour compter le nombre de lignes d'un projet.

$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
Total Lines: 37328

-s --syntax-highlight et --syntax-highlighting

Affiche le code avec la colorisation syntaxique.

Cette option utilise le mécanisme interne pour analyser le fichier, et produire une version colorisée du code source, au format HTML. Notez que cette option ne fait que générer un bloc HTML, avec les balises HTML <code> [...] </code>, sans en-têtes HTML.

Note: Cette option ne fonctionne pas avec l'option -r.

-v --version

Affiche les versions de PHP, PHP SAPI, et Zend sur la sortie standard. Par exemple :

$ php -v
PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-w --strip

Affiche la source sans les commentaires et les espaces.

Note: Cette option ne fonctionne pas avec l'option -r.

-z --zend-extension

Charge une extension Zend. Si et seulement si un fichier est fourni, PHP essaie de charger cette extension dans le dossier courant par défaut des bibliothèque sur votre système (généralement spécifié avec /etc/ld.so.conf sous Linux). Passer un nom de fichier avec le chemin complet fera que PHP utilisera ce fichier, sans recherche dans les dossiers classiques. Un chemin de dossier relatif indiquera à PHP qu'il doit chercher les extensions uniquement dans ce dossier.

  --ini

Affiche les noms des fichiers de configuration et des dossiers analysés. Disponible depuis PHP 5.2.3.

Exemple #3 Exemple avec --ini

$ php --ini
Configuration File (php.ini) Path: /usr/dev/php/5.2/lib
Loaded Configuration File:         /usr/dev/php/5.2/lib/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

--rf --rfunction

Affiche des informations sur la fonction donnée ou la méthode d'une classe (i.e. nombre et nom des paramètres). Disponible depuis PHP 5.1.2.

Cette option n'est disponible que si PHP a été compilé avec le support Reflection.

Exemple #4 Exemple avec --rf

$ php --rf var_dump
Function [ <internal> public function var_dump ] {

- Parameters [2] {
Parameter #0 [ <required> $var ]
Parameter #1 [ <optional> $... ]
}
}

--rc --rclass

Affiche des informations sur la classe donnée (liste des constantes, propriétés et méthodes). Disponible depuis PHP 5.1.2.

Cette option n'est disponible que si PHP a été compilé avec le support Reflection.

Exemple #5 Exemple avec --rc

$ php --rc Directory
Class [ <internal:standard> class Directory ] {

  - Constants [0] {
  }

  - Static properties [0] {
  }

  - Static methods [0] {
  }

  - Properties [0] {
  }

  - Methods [3] {
    Method [ <internal> public method close ] {
    }

    Method [ <internal> public method rewind ] {
    }

    Method [ <internal> public method read ] {
    }
  }
}

--re --rextension

Affiche les informations sur l'extension donné (liste les options du php.ini, les fonctions définies, les constantes et les classes). Disponible depuis PHP 5.1.2.

Cette option n'est disponible que si PHP a été compilé avec le support Reflection.

Exemple #6 Exemple avec --re

$ php --re json
Extension [ <persistent> extension #19 json version 1.2.1 ] {

  - Functions {
    Function [ <internal> function json_encode ] {
    }
    Function [ <internal> function json_decode ] {
    }
  }
}

--ri --rextinfo

Affiche les informations de configuration pour l'extension donnée (les mêmes informations retournées par la fonction phpinfo()). Disponible depuis PHP 5.2.2. Les informations de configurations internes sont disponibles en utilisant le nom d'extension "main".

Exemple #7 Exemple avec --ri

$ php --ri date

date

date/time support => enabled
"Olson" Timezone Database Version => 2007.5
Timezone Database => internal
Default timezone => Europe/Oslo

Directive => Local Value => Master Value
date.timezone => Europe/Oslo => Europe/Oslo
date.default_latitude => 59.22482 => 59.22482
date.default_longitude => 11.018084 => 11.018084
date.sunset_zenith => 90.583333 => 90.583333
date.sunrise_zenith => 90.583333 => 90.583333

L'exécutable PHP peut être utilisé pour exécuter des scripts indépendants du serveur web. Si vous êtes sur un système Unix, il est recommandé d'ajouter la ligne spéciale en début de script, de le rendre exécutable de manière à ce que le système sache quel programme doit exécuter le script. Sous Windows, vous pouvez associer l'exécutable php.exe avec le double-clic sur les fichiers d'extension .php, ou bien vous pouvez faire un fichier batch pour exécuter le script grâce à PHP. La première ligne utilisée dans le monde Unix ne perturbera pas l'exécution sous Windows, ce qui rend les scripts facilement portables. Un exemple complet est disponible ci-dessous :

Exemple #8 Script prévu pour être exécuté en ligne de commande (script.php)

<?php

if ($argc != || in_array($argv[1], array('--help''-help''-h''-?'))) {
?>

C'est une ligne de commande à une option.

Utilisation :
<?php echo $argv[0]; ?> <option>

<option> peut être un mot que vous souhaitez afficher.
Avec les options --help, -help, -h,
et -?, vous obtiendrez cette aide.

<?php
} else {
  echo 
$argv[1];
}
?>

Dans le script ci-dessus, nous utilisons la première ligne pour indiquer que le fichier doit être exécuté par PHP. Nous travaillons avec une version CLI, donc aucun en-tête HTTP n'est affiché. Il y a deux variables que vous pouvez utiliser avec les applications de ligne de commande : $argc et $argv. La première est le nombre d'arguments plus un (le nom du script qui est exécuté). La seconde est un tableau contenant les arguments, commençant avec le nom du script en élément 0 ($argv[0]).

Dans notre exemple, nous avons vérifié qu'il y a plus ou moins d'un argument. De plus, si cet argument est --help, -help, -h ou -?, nous affichons un message d'aide, ainsi que le nom du script. Si nous recevons un autre argument, celui-ci est affiché dans le terminal.

Pour exécuter le script ci-dessus sous Unix, vous devez le rendre exécutable, puis l'appeler avec une commande comme : script.php echothis ou script.php -h. Sous Windows, vous pouvez faire un fichier batch pour cela :

Exemple #9 Fichier batch pour exécuter un script PHP en ligne de commande (script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

Si vous avez nommé le programme ci-dessus script.php, et que vous avez votre exécutable php.exe situé à C:\php\php.exe, ce fichier batch l'exécutera avec les options que vous lui passez : script.bat echothis ou script.bat -h.

Voir aussi l'extension Readline, qui dispose de nombreuses fonctions pour améliorer la convivialité de vos applications en ligne de commande.



add a note add a note User Contributed Notes
Utiliser PHP en ligne de commande
ca at php dot spamtrak dot org
08-Oct-2009 11:06
I append this to most of my PHP files, to allow command line unit testing of a class.  It ensures that the unit test is only run if the script is run directly, and won't be triggered by an include from another CLI script.

<?php
if (!empty($argc) && strstr($argv[0], basename(__FILE__))) {
  
$test = new TestClass();
  
$rv = $test->Test();
   die(
"Test returned $rv\n");
}
?>
dj dot rokx at gmail dot com
11-Sep-2009 08:34
Use PHP as Scripting Language in Windows Vista and 7:

ASSOC .phs=PHPScript
FTPYE PHPScript=[path to]\php.exe -f "%1" -- %*

optional set PATHEXT=.phs;%PATHEXT%

now you can execute any php-script (ext: .phs) from the shell like a .vbs or .cmd.

"c:\testscript.phs arg1 arg2" or with the optional step "c:\testscript arg1 arg2"

i hope this helps somebody.
Wade
07-Sep-2009 05:46
I've just found that the fact that the CLI does *not* change the current directory will make include() and require() calls with relative paths fail. This is because they are relative to the current directory, not to the current executing file, the documentation notwithstanding. In CGI mode, this is the same because it changes the current directory.

One solution is to call the CGI binary rather than the CLI one. A better solutions is to use dirname(__FILE__) in your path names.
fuzzy76 at fuzzy76 dot net
30-Aug-2009 04:30
To detect if run from CLI:

if (defined('STDIN'))

or:

if (isset($argc))
patrick at pwfisher dot com
22-Aug-2009 06:59
This command line option parser supports any combination of three types of options (switches, flags and arguments) and returns a simple array.

[pfisher ~]$ php test.php --foo --bar=baz
  ["foo"]   => true
  ["bar"]   => "baz"

[pfisher ~]$ php test.php -abc
  ["a"]     => true
  ["b"]     => true
  ["c"]     => true

[pfisher ~]$ php test.php arg1 arg2 arg3
  [0]       => "arg1"
  [1]       => "arg2"
  [2]       => "arg3"

<?php
function parseArgs($argv){
   
array_shift($argv);
   
$out = array();
    foreach (
$argv as $arg){
        if (
substr($arg,0,2) == '--'){
           
$eqPos = strpos($arg,'=');
            if (
$eqPos === false){
               
$key = substr($arg,2);
               
$out[$key] = isset($out[$key]) ? $out[$key] : true;
            } else {
               
$key = substr($arg,2,$eqPos-2);
               
$out[$key] = substr($arg,$eqPos+1);
            }
        } else if (
substr($arg,0,1) == '-'){
            if (
substr($arg,2,1) == '='){
               
$key = substr($arg,1,1);
               
$out[$key] = substr($arg,3);
            } else {
               
$chars = str_split(substr($arg,1));
                foreach (
$chars as $char){
                   
$key = $char;
                   
$out[$key] = isset($out[$key]) ? $out[$key] : true;
                }
            }
        } else {
           
$out[] = $arg;
        }
    }
    return
$out;
}
?>

Full version with comments here: http://pwfisher.com/nucleus/index.php?itemid=45
coffear at gmail dot com
07-Jun-2009 12:06
In the notes it there is an example of running 1 line of PHP using:

php -r 'print_r(get_defined_constants());'

This might work on a UNIX machine but unfortunately on windows it produces the following error message:

Parse error: parse error in Command line code on line 1

Instead of using ' (single quotes) to encompass the PHP code use " (double quotes) instead. You can safely use ' within the code itself however such as:

php -r "echo 'hello';"
SEWilco
07-May-2009 04:23
Notice that piping output to some programs will have unexpected behavior:
               php my_script.php | less

The 'less' program usually sets the terminal mode so pressing ENTER is not necessary.  When using php-cli, it is necessary to press ENTER, unless "!stty sane" is able to fix things for you.  The php command is doing something to the terminal mode despite no interactive shell being requested.
Willy T. Koch
24-Feb-2009 10:11
I'm figuring out how to pipe an email to a php script with postfix. For the email user@example.com:

I created the following line in /etc/aliases:
user:        "|/www/file.php"

file.php is chmod 755

This works fine. But I wanted to test this without having to send an email every time. And this took some searching to figure out, yet it's oh-so simple:

To pipe the file email.txt to the script, write the following in the terminal window:

user@host: php file.php < testepost.txt

I was confused by the | in the aliases file, and didn't get what came after what, etc etc.

Regards,

Willy T. Koch
Norway
patrick smith
11-Nov-2008 03:43
For command-line option definition and parsing, don't forget about the beauty of getopt().

There's a php-native version (http://php.net/getopt) and a PEAR package -- Console_GetOpt (http://pear.php.net/package/Console_Getopt).
Anonymous
26-Oct-2008 04:52
Here's  my modification of "thomas dot harding at laposte dot net" script (below) to read arguments from $argv of the form --name=VALUE and -flag.

"Input":
./script.php -a arg1 --opt1 arg2 -bcde --opt2=val2 arg3 arg4 arg5 -fg --opt3

"print_r Output":
Array
(
    [exec] => ./script.php
    [options] => Array
        (
            [0] => opt1
            [1] => Array
                (
                    [0] => opt2
                    [1] => val2
                )
            [2] => opt3
        )
    [flags] => Array
        (
            [0] => a
            [1] => b
            [2] => c
            [3] => d
            [4] => e
            [5] => f
            [6] => g
        )
    [arguments] => Array
        (
            [0] => arg1
            [1] => arg2
            [2] => arg3
            [3] => arg4
            [4] => arg5
        )
)

<?php
function arguments($args ) {
   
$ret = array(
       
'exec'      => '',
       
'options'   => array(),
       
'flags'     => array(),
       
'arguments' => array(),
    );

   
$ret['exec'] = array_shift( $args );

    while ((
$arg = array_shift($args)) != NULL) {
       
// Is it a option? (prefixed with --)
       
if ( substr($arg, 0, 2) === '--' ) {
           
$option = substr($arg, 2);

           
// is it the syntax '--option=argument'?
           
if (strpos($option,'=') !== FALSE)
               
array_push( $ret['options'], explode('=', $option, 2) );
            else
               
array_push( $ret['options'], $option );
           
            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
       
$ret['arguments'][] = $arg;
        continue;
    }
    return
$ret;
}
//function arguments
?>
tom at thomas dot harding dot net
04-Oct-2008 12:27
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
thomas dot harding at laposte dot net
14-Jun-2008 10: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: */
?>
mortals at seznam dot cz
07-May-2008 08: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
safak ozpinar
29-Feb-2008 02: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);

?>
Anonymous
17-Feb-2008 05: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 ) );

?>
technorati at gmail dot com
12-Feb-2008 02: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

<?php
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;
}
?>
earomero _{at}_ gmail.com
28-Oct-2007 11: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
)
james_s2010 at NOSPAM dot hotmail dot com
22-Oct-2007 09: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.
B Crawford
22-Oct-2007 02: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
)

*/
?>
losbrutos at free dot fr
27-Sep-2007 12: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
)
dino (at) asttra (dot) com (dot) br
16-Aug-2007 07: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");
lucas dot vasconcelos at gmail dot com
22-Jul-2007 06:04
Just another variant of previous script that group arguments doesn't starts with '-' or '--'

<?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';
      } else {
           
$_ARG['input'][]=$arg;
      }
    }
  return
$_ARG;
}

print_r(arguments($argv));
?>

$ 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
)
bluej100@gmail
25-Jun-2007 06: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.
eric dot brison at anakeen dot com
04-Jun-2007 12: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
)
contact at nlindblad dot org
12-May-2007 09: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
)
Jouni
08-Apr-2007 10: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.
rob
23-Mar-2007 07: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 editingthe '-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...
djcassis at gmail
09-Mar-2007 03: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
jgraef at users dot sf dot net
26-Nov-2006 04: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;
  }
?>
goalain eat gmail dont com
14-Nov-2006 08: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
16-Sep-2006 06:05
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.
hobby6_at_hotmail.com
15-Sep-2006 10: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";
?>
stromdotcom at hotmail dot com
21-Feb-2006 06: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
drewish at katherinehouse dot com
25-Sep-2005 07: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'));"
OverFlow636 at gmail dot com
19-Sep-2005 07: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];
    }
}
?>
php at schabdach dot de
16-Sep-2005 04: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.
docey
14-Jul-2005 12: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.
wallacebw
24-Jun-2005 03: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:

<?php
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
linus at flowingcreativity dot net
30-May-2005 02: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!
roberto dot dimas at gmail dot com
26-May-2005 08: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
diego dot rodrigues at poli dot usp dot br
03-May-2005 03:29
#!/usr/bin/php -q
<?php
/**********************************************
* 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;
                        }
                    }
                }
               
//We have passed -xxxxx1 xxxxx2
               
array_push($this->parsed,
                                                  array(
$this->argv[$i]) );
            }
        }

               
//Testing if all necessary parameters have been passed
               
$this->force();
    }

   
//Testing if one parameter have benn passed
   
function passed($argumento) {
        for(
$i=0 ; $i< $this->argc ; $i++)
            if (
$this->parsed[$i][0] == $argumento )
                return
$i;
        return
0;
    }

   
//Testing if you have passed a estra argument, -xxxx1 xxxxx2
   
function full_passed($argumento) {
       
$findArg = $this->passed($argumento);
        if (
$findArg )
            if (
count($this->parsed[$findArg] ) > 1 )
                return
$findArg;
        return
0;
    }

       
//Returns  xxxxx2 at a " -xxxx1 xxxxx2" call
   
function get_full_passed($argumento) {
               
$findArg = $this->full_passed($argumento);

                if (
$findArg )
                    return
$this->parsed[$findArg][1];

                return;
        }
   
   
//Necessary parameters to script
   
function force() {
        if (
is_array( $this->force_this ) ) {
            for(
$i=0 ; $i< count($this->force_this) ; $i++) {
                if (
$this->force_this[$i][1] == "SIMPLE"
                    
&& !$this->passed($this->force_this[$i][0])
                )
                    die(
"\n\nMissing " . $this->force_this[$i][0] . "\n\n");

                                if (
$this->force_this[$i][1] == "FULL"
                                    
&& !$this->full_passed($this->force_this[$i][0])
                )
                                        die(
"\n\nMissing " . $this->force_this[$i][0] ." <arg>\n\n");
            }
        }
    }
}

//Example
$forcar = array(
        array(
"-name", "FULL"),
        array(
"-email","SIMPLE") );

$parser = new arg_parser($forcar);

if (
$parser->passed("-show") )
    echo
"\nGoing...:";

echo
"\nName: " . $parser->get_full_passed("-name");

if (
$parser->full_passed("-email") ) 
    echo
"\nEmail: " . $parser->get_full_passed("-email");
else
        echo
"\nEmail: default";

if (
$parser->full_passed("-copy") )
        echo
"\nCopy To: " . $parser->get_full_passed("-copy");

echo
"\n\n";
?>

TESTING
=====
[diego@Homer diego]$ ./en_arg_parser.php -name -email cool -copy Ana

Missing -name <arg>

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email cool -copy Ana

Name: diego
Email: cool
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email  -copy Ana

Name: diego
Email: default
Copy To: Ana

[diego@Homer diego]$ ./en_arg_parser.php -name diego -email

Name: diego
Email: default

[diego@Homer diego]$
rh@hdesigndotdemondotcodotuk
25-Apr-2005 08:28
In a bid to save time out of lives when calling up php from the Command Line on Mac OS X.

I just wasted hours on this. Having written a routine which used the MCRYPT library, and tested it via a browser, I then set up a crontab to run the script from the command line every hour (to do automated backups from mysql using mysqldump, encrypt them using mcrypt, then email them and ftp them off to remote locations).

Everything worked fine from the browser, but failed every time from the cron task with "Call to undefined function: mcrypt [whatever]".

Only after much searching do I realise that the CGI and CLI versions are differently compiled, and have different modules attached (I'm using the entropy.ch install for Mac OS-X, php v4.3.2 and mysql v4.0.18).

I still can not find a way to resolve the problem, so I have decided instead to remove the script from the SSL side of the server, and run it using a crontab with CURL to localhost or 127.0.0.1 in order that it will run through Apache's php module.

Just thought this might help some other people tearing their hair out. If anyone knows a quick fix to add the mcrypt module onto the CLI php without any tricky re-installing, it'd be really helpful.

Meantime the workaround does the job, not as neatly though.
merrittd at dhcmc dot com
28-Mar-2005 09:23
Example 43-2 shows how to create a DOS batch file to run a PHP script form the command line using:

@c:\php\cli\php.exe script.php %1 %2 %3 %4

Here is an updated version of the DOS batch file:

@c:\php\cli\php.exe %~n0.php %*

This will run a PHP file (i.e. script.php) with the same base file name (i.e. script) as the DOS batch file (i.e. script.bat) and pass all parameters (not just the first four as in example 43-2) from the DOS batch file to the PHP file. 

This way all you have to do is copy/rename the DOS batch file to match the name of your PHP script file without ever having to actually modify the contents of the DOS batch file to match the file name of the PHP script.
bertrand at toggg dot com
07-Mar-2005 04:40
If you want to pass directly PHP code to the interpreter and you don't have only CGI, not the CLI SAPI so you miss the -r option.
If you're lucky enough to be on a nix like system, then tou can still use the pipe solution as the 3. way to command CLI SAPI described above, using a pipe ('|').

Then works for CGI SAPI:

$ echo '<?php echo "coucou\n"; phpinfo(); /* or any code */ ?>' | php

NOTE: unlike commands passed to the -r option, here you NEED the PHP tags.
obfuscated at emailaddress dot com
25-Feb-2005 04:15
This posting is not a php-only problem, but hopefully will save someone a few hours of headaches.  Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:

[macg4:valencia/jobs] tim% test.php
./test.php: Command not found.

However, it worked just fine when php was envoked on the command line:

[macg4:valencia/jobs] tim% php test.php
Well, here we are...  Now what?

Was file access mode set for executable?  Yup.

[macg4:valencia/jobs] tim% ls -l
total 16
-rwxr-xr-x  1 tim  staff   242 Feb 24 17:23 test.php

And you did, of course, remember to add the php command as the first line of your script, yeah?  Of course.

#!/usr/bin/php
<?php print "Well, here we are...  Now what?\n"; ?>

So why dudn't it work?  Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)...  Using, say, WordPad on Windows... and BBEdit on the Mac...

Aaahhh... in BBEdit check how the file is being saved!  Mac?  Unix?  or Dos?  Bingo.  It had been saved as Dos format.  Change it to Unix:

[macg4:valencia/jobs] tim% ./test.php
Well, here we are...  Now what?
[macg4:valencia/jobs] tim%

NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format...  those \r's and \n's 'll bite cha!
db at digitalmediacreation dot ch
22-Feb-2005 07:49
A very important point missing here (I lost hours on it and hope to avoid this to you) :

* When using PHP as CGI
* When you just become crazy because of "No input file specified" appearing on the web page, while it never appears directly in the shell

Then I have a solution for you :

1. Create a script for example called cgiwrapper.cgi
2. Put inside :
 #!/bin/sh -
 export SCRIPT_FILENAME=/var/www/realpage.php
 /usr/bin/php -f $SCRIPT_FILENAME
3. Name your page realpage.php

For example with thttpd the problem is that SCRIPT_FILENAME is not defined, while PHP absolutely requires it.
My solution corrects that problem !
ken.gregg at rwre dot com
09-Jan-2005 09:38
If you want to use named command line parameters in your script,
the following code will parse command line parameters in the form
of name=value and place them in the $_REQUEST super global array.

cli_test.php
<?php

echo "argv[] = ";
print_r($argv);  // just to see what was passed in

if ($argc > 0)
{
  for (
$i=1;$i < $argc;$i++)
  {
   
parse_str($argv[$i],$tmp);
   
$_REQUEST = array_merge($_REQUEST, $tmp);
  }
}

echo
"\$_REQUEST = ";
print_r($_REQUEST);

?>

rwre:~/tmp$ /usr/local/bin/php cli_test.php foo=1 bar=2 third=a+value

argv[] = Array
(
    [0] => t.php
    [1] => foo=1
    [2] => bar=2
    [3] => third=a+value
)
$_REQUEST = Array
(
    [foo] => 1
    [bar] => 2
    [third] => a value
)
Ben Jenkins
22-Dec-2004 05:23
This took me all day to figure out, so I hope posting it here saves someone some time:
Your PHP-CLI may have a different php.ini than your apache-php.  For example: On my Debian-based system, I discovered I have /etc/php4/apache/php.ini and /etc/php4/cli/php.ini
If you want MySQL support in the CLI, make sure the line
extension=mysql.so
is not commented out.
The differences in php.ini files may also be why some scripts will work when called through a web browser, but will not work when called via the command line.
linn at backendmedia dot com
06-Feb-2004 02:12
For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
chdir(dirname($_SERVER['argv'][0]));

at the beginning of your scripts.
ben at slax0rnet dot com
03-Feb-2004 03:34
Just a note for people trying to use interactive mode from the commandline.

The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:

[root@localhost php-4.3.4]# php -a
Interactive mode enabled

<?php echo "hi!"; ?>
<note, here we would press CTRL-D to parse everything we've entered so far>
hi!
<?php exit(); ?>
<ctrl-d here again>
[root@localhost php-4.3.4]#

I noticed this somehow got ommited from the docs, hope it helps someone!
phprsr at mindtwin dot com
06-Aug-2003 04:12
The basic issue was that PHP-as-CGI REALLY REALLY wants SCRIPT_FILENAME.
It ignores the command line. It ignores SCRIPT_NAME.  It wants
SCRIPT_FILENAME.

"No input file specified."

This very informative error message from PHP means that your web server, WHATEVER it is, is not setting SCRIPT_FILENAME.

The minimum set of env variables:

PATH: DOESN'T MATTER if you're spawning php pages with #!/../php in them
LD_LIBRARY_PATH= should be right
SERVER_SOFTWARE=mini_httpd/1.17beta1 26may2002
SERVER_NAME=who cares
GATEWAY_INTERFACE=CGI/1.1
SERVER_PROTOCOL=HTTP/1.0
SERVER_PORT=whatever
REQUEST_METHOD=GET
SCRIPT_NAME=/foo.php
SCRIPT_FILENAME=/homes/foobie/mini/foo.php    <--- CRITICAL
QUERY_STRING==PHPE9568F35-D428-11d2-A769-00AA001ACF42
REMOTE_ADDR=172.17.12.80
HTTP_REFERER=http://booky16:10000/foo.php
HTTP_USER_AGENT=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; Q312461; .NET CLR 1.0.3705; .NET CLR 1.1.4322)

If SCRIPT_FILENAME is not set, you'll get the dreaded "No input file specified" message.

mini_httpd does not do this by default. You need to patch it in to make_envp.

A secondary issue is configuration (PHP):

    ./configure --enable-discard-path --with-config-file-path=/homes/wherever/mini/php.ini
   
    (where php.ini is a slightly modified version of php.ini-recommended)
punk at studionew dot com
19-Jul-2003 11:18
You can use this function to ask user to enter something.

<?php
function read ($length='255')
{
   if (!isset (
$GLOBALS['StdinPointer']))
   {
     
$GLOBALS['StdinPointer'] = fopen ("php://stdin","r");
   }
  
$line = fgets ($GLOBALS['StdinPointer'],$length);
   return
trim ($line);
}

// then

echo "Enter your name: ";
$name = read ();
echo
"\nHello $name! Where you came from? ";
$where = read ();
echo
"\nI see. $where is very good place.";
?>
Adam, php(at)getwebspace.com
17-Jun-2003 11:12
Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
---
No input file specified.
---

And the CLI version would return:
---
500 Internal Server Error
---

It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.

By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
monte at ispi dot net
04-Jun-2003 10:47
I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.

Monte
Popeye at P-t-B dot com
18-Apr-2003 03:15
In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.

example:

# which php
/usr/local/bin/php
# php -v
PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
Copyright (c) 1997-2002 The PHP Group
Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

In the above example, you would use: #!/usr/local/bin/php

Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
volkany at celiknet dot com
20-Feb-2003 09:44
Here goes a very simple clrscr function for newbies...
function clrscr() { system("clear"); }
Alexander Plakidin
14-Feb-2003 01:34
How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
(you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)

Here's what I am using:
chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));

Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...

Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
c dot kelly[no--spam] at qfsaustrlia dot com dot au
07-Feb-2003 04:03
In Windows [NT4.0 sp6a] the example
php -r ' echo getcwd();' does not work ; It appears you have to use the following php -r "echo getcwd();" --not the " around the command   to get the output to screen , just took me half an hour to figure out what was going on.
wanna at stay dot anonynous dot com
22-Jan-2003 05:42
TIP: If you want different versions of the configuration file  depending on what SAPI is used,just name them php.ini (apache module), php-cli.ini (CLI) and php-cgi.ini (CGI) and dump them all in the regular configuration directory. I.e no need to compile several versions of php anymore!
phpnotes at ssilk dot de
22-Oct-2002 10:36
To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call

php myprog.html '&hugo=bla&bla=hugo'

(two & instead of ? and &!)

There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
justin at visunet dot ie
21-Oct-2002 04:21
If you are trying to set up an interactive command line script and you want to get started straight away (works on 4+ I hope). Here is some code to start you off:

<?php

   
// Stop the script giving time out errors..
   
set_time_limit(0);

   
// This opens standard in ready for interactive input..
   
define('STDIN',fopen("php://stdin","r"));

   
// Main event loop to capture top level command..
   
while(!0)
    {
       
       
// Print out main menu..
       
echo "Select an option..\n\n";
        echo
"    1) Do this\n";
        echo
"    2) Do this\n";
        echo
"    3) Do this\n";
        echo
"    x) Exit\n";

       
// Decide what menu option to select based on input..
       
switch(trim(fgets(STDIN,256)))
        {
            case
1:
                break;
               
            case
2:
                break;

            case
3:
                break;

            case
"x":
                exit();
               
            default:
                break;
        }

    }

   
// Close standard in..
   
fclose(STDIN);

?>
phpNOSPAM at dogpoop dot cjb dot net
12-Oct-2002 03:28
Here are some instructions on how to make PHP files executable from the command prompt in Win2k.  I have not tested this in any other version of Windows, but I'm assuming it will work in XP, but not 9x/Me.

There is an environment variable (control panel->system->advanced->environment variables) named PATHEXT.  This is a list of file extensions Windows will recognize as executable at the command prompt.  Add .PHP (or .PL, or .CLASS, or whatever) to this list.  Windows will use the default action associated with that file type when you execute it from the command prompt.

To set up the default action:
Open Explorer.
Go to Tools->folder options->file types
Find the extension you're looking for.  If it's not there, click New to add it.
Click on the file type, then on Advanced, then New.
For the action, type "Run" or "Execute" or whatever makes sense.
For the application, type
  {path to application} "%1" %*
The %* will send any command line options that you type to the program.
The application field for PHP might look like
  c:\php\php.exe -f "%1" -- %*
(Note, you'll probably want to use the command line interface version php-cli.exe)
or for Java
  c:\java\java.exe "%1" %*
Click OK.
Click on the action that was just added, then click Set default.

If this helps you or if you have any changes/more information I would appreciate a note.  Just remove NOSPAM from the email address.
jeff at noSpam[] dot genhex dot net
06-Sep-2002 12:13
You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).

On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located).  If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
zager[..A..T..]teleaction.de
15-Aug-2002 06:15
Under Solaris (at least 2.6) I have some problems with reading stdin. Original pbms report may be found here:
http://groups.google.com/groups?
q=Re:+%5BPHP%5D+Q+on+php://stdin+--+an+answer!&hl=en&lr=&ie=UTF-
8&oe=UTF-8&selm=3C74AF57.6090704%40Sun.COM&rnum=1

At a first glance the only solution for it is 'fgetcsv'

#!/usr/local/bin/php -q
<?php

set_magic_quotes_runtime
(0);
$fd=fopen("php://stdin","r");
if (!
$fd)
  exit;

while (!
feof ($fd))
{
 
$s = fgetcsv($fd,128,"\n");
  if (
$s==false)
    continue;

  echo
$s[0]."\n";
}
?> 

But... keep reading....

>>> I wrote
Hello,
Sometimes I hate PHP... ;)

Right today I was trapped by some strange bug in my code with reading stdin using fgetcsv.
After a not small investigation I found that strings like "foo\nboo\ndoo"goo\n (take note of double quatation sign in it)
interpreted by fgetcsv like:
1->foo\nboo\ndoo
2->goo
since double quotation mark has a special meaning and get stripped off of the input stream.
Indeed, according to PHP manual:
[quote]
array fgetcsv ( int fp, int length [, string delimiter [, string enclosure]])

[skip]
another delimiter with the optional third parameter. _The_enclosure_character_is_double_quote_,_unless_
it_is_specified_.
[skip]
_enclosure_is_added_from_PHP 4.3.0.       !!!!!!
[/quote]

Means no chance for us prior to 4.3.0 :(
But file() works just fine !!!! Of course by the price of memory, so be careful with large files.

set_magic_quotes_runtime(0); // important, do not forget it !!!
$s=file("php://stdin");
for ($i=0,$n=sizeof($s);$i<$n;$i++)
{
  do_something_useful(rtrim($s[$i]));
}

Conclusion:
1. If you have no double quotation mark in your data use fgetcsv
2. From 4.3.0 use   fgetcsv($fd,"\n",""); // I hope it will help
3. If you data is not huge use file("php://stdin");

Hope now it's cleared for 100% (to myself ;)

Good luck!
Dim

PS. Don't forget that it's only Solaris specific problem. Under Linux just use usual fgets()...
jonNO at SPAMjellybob dot co dot uk
04-Aug-2002 04:17
If you want to get the output of a command use the function shell_exec($command) - it returns a string with the output of the command.
ben-php dot net at wefros dot com
13-Jun-2002 10:40
PHP 4.3 and above automatically have STDOUT, STDIN, and STDERR openned ... but < 4.3.0 do not.  This is how you make code that will work in versions previous to PHP 4.3 and future versions without any changes:

<?php
   
if (version_compare(phpversion(),'4.3.0','<')) {
       
define('STDIN',fopen("php://stdin","r"));
       
define('STDOUT',fopen("php://stout","r"));
       
define('STDERR',fopen("php://sterr","r"));
       
register_shutdown_function( create_function( '' , 'fclose(STDIN); fclose(STDOUT); fclose(STDERR); return true;' ) );
    }

/* get some STDIN up to 256 bytes */
   
$str = fgets(STDIN,256);
?>
pyxl at jerrell dot com
18-Feb-2002 07:52
Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild.  If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.

 
show source | credits | sitemap | contact | advertising | mirror sites