PHP: Pou�it� PHP z p��kazov� ��dky - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<Bezpe�n� re�imReference funkc�>
view the version of this page
Last updated: Thu, 15 Jul 2004

Kapitola 25. Pou�it� PHP z p��kazov� ��dky

Mo�nosti PHP p�i spou�t�n� z p��kazov� ��dky p�in�ej� mnoho u�itku, pokud chcete ladit nebo testovat va�e nastaven� PHP, hod� se v�ak i pro p��pady, kdy byste r�di pou�ili PHP pro jin� ��ely ne� WWW skriptov�n�.

Uv�domte si, �e m��ete v�dy sm�rovat v�stup programu PHP do vn�j��ho souboru pomoc� znaku >, tak�e php -q test.php > test.html vytiskne v�stup test.php bez HTTP hlavi�ek do test.html ve stejn�m adres��i.

Mo�nosti p��kazov� ��dky m��ete vyu��vat pouze tehdy, m�te-li (spustiteln�) program PHP. Pokud jste zkompilovali pouze modul do serveru a nem�te na po��ta�i ��dnou CGI verzi, nem��ete p��kazovou ��dku pou��vat. Pro u�ivatele Windows je v bin�rn�m bal��ku jak serverov� modul, tak spustiteln� soubor nazvan� php.exe.

Tento seznem voleb pro p��kazovou ��dku je konzistentn� s PHP 4.0.6. Aktu�ln� seznam v�etn� jedno��dkov�ch popis� m��ete z�skat pomoc� parametru -h. V�stup php -h by m�l vypadat p�ibli�n� takto:
Usage: php [-q] [-h] [-s [-v] [-i] [-f <file>] |  {<file> [args...]}
  -q             Quiet-mode.  Suppress HTTP Header output.
  -s             Display colour syntax highlighted source.
  -f <file>      Parse <file>.  Implies `-q'
  -v             Version number
  -C             Do not chdir to the script's directory
  -c <path>      Look for php.ini file in this directory
  -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
  -h             This help

Zde uv�d�me n�kter� z nejd�le�it�j��ch voleb s detailn�m vysv�tlen�m.

Tabulka 25-1. Volby pro p��kazovou ��dku

VolbaPopis
-q Potla�� v�stup HTTP hlavi�ek. Norm�ln� PHP tiskne HTTP hlavi�ky pro volaj�c� program (typicky WWW server) k p�ed�n� prohl�e�i. P�i pou�it� pro aplikace spou�t�n� z p��kazov� ��dky nemaj� hlavi�ky smysl.
-s Zobraz� barevn� vysv�cen� zdrojov� soubor s dan�m n�zvem. Je to tot�, jako kdy� se zdroj vytiskne pomoc� funkce highlight_file() v PHP skriptu.
-f Parsuje dan� soubor a hled� syntaktick� a fat�ln� chyby. Tato volba implikuje -q. Pou�ijte pro ladic� ��ely (debugging).
-v Zavol�n�m PHP s t�mto p�ep�na�em si m��ete vypsat ��slo verze, nap�. 4.0.6.
-C Za norm�ln�ch okolnost� PHP m�n� pracovn� adres�� na ten, kde se nach�z� spou�t�n� skript. To nap��klad umo��uje otv�rat soubory ve stejn�m adres��i ur�en�m pouh�ho n�zvu souboru (bez cesty). Pokud byste toto cht�li potla�it, pou�ijte tuto volbu.
-c Pou�it�m tohoto argumentu m��ete specifikovat alternativn� um�st�n� souboru php.ini, tak�e PHP bude hledat konfigura�n� soubor zde nam�sto implicitn�ho um�st�n�.
-d Touto volbou m��ete prov�st individu�ln� nastaven� php.ini b�hem prov�d�n� skriptu.
-l Otestuje dan� soubor na syntaktick� chyby. Tato volba implikuje -q. Pou�ijte ji pro ��ely lad�n�. Nebudou se hledat fat�ln� chyby (jako jsou nedefinovan� funkce). Pokud chcete hledat i fat�ln� chyby, pou�ijte -f.
-m Pou�it�m t�to volby PHP vyp�e zabudovan� (a na�ten�) PHP a Zend moduly, ��sla verz� PHP a Zend, a tak� kr�tkou informaci o autorsk�ch pr�vech k j�dru Zend.
-i Tento p�ep�na� zavol� funkci phpinfo() a vyp�e jej� v�sledek. Pokud PHP nepracuje spr�vn�, je dobr� spustit php -i a pod�vat se, zda se nevypsala n�jak� chybov� hl�en� p�ed nebo uvnit� informa�n�ch tabulek.
-h Touto volbou z�sk�te informace o aktu�ln�ch volb�ch p��kazov� ��dky a jedno��dkov� popisy o tom, co d�laj�.

Spustiteln� verze PHP m��e b�t pou�ita pro spou�t�n� skript� absolutn� nez�visle na webovsk�m serveru. Pokud jste na unixov�m syst�mu, m��ete do PHP skriptu p�idat speci�ln� prvn� ��dek a ud�lat z n�j spustiteln� program - syst�m bude v�d�t, jak� program by m�l skript zpracov�vat. Na Windows m��ete asociovat php.exe -q se souborovou p��ponou .php (pro spou�t�n� dvojklikem), nebo m��ete vytvo�it d�vkov� soubor pro spu�t�n� skriptu p�es PHP. Prvn� ��dek skriptu pro pr�ci v Unixu nebude ve Windows vadit, tak�e t�mto zp�sobem m��ete ps�t programy pro v�ce platforem. Jednoduch� p��klad psan� PHP programu pro p��kazovou ��dku je uveden n�e.

P��klad 25-1. Skript ur�en� ke spou�t�n� z p��kazov� ��dky (script.php)

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

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

This is a command line PHP script with one option.

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

  <option> can be some word you would like
  to print out. With the --help, -help, -h,
  or -? options, you can get this help.

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

Ve v��e uveden�m skriptu jsme pou�ili speci�ln� prvn� ��dek k indikaci, �e by tento soubor m�l b�t spou�t�n pomoc� PHP a nem�l by vypisovat HTTP hlavi�ky. Jsou zde dv� prom�nn�, kter� m��ete pou��t p�i psan� aplikac� pro PHP spou�t�n�ch z p��kazov� ��dky: $argc a $argv. Prvn� z nich je po�et argument� + 1 (n�zev b��c�ho skriptu). Druh� je pole obsahuj�c� argumenty, po��naje n�zvem skriptu jako ��slo 0 ($argv[0]).

V uk�zkov�m programu se testuje, zda je argument� v�ce �i m�n� ne� jeden. Pokud by argument byl --help, -help, -h nebo -?, vytiskne se n�pov�da k programu v�etn� skute�n�ho n�zvu skriptu. Pokud by byly p�id�ny n�jak� dal�� argumenty, vytisknou se na v�stup.

Pokud byste cht�li spou�t�t uveden� skript pod Unixem, mus�te ho ud�lat spustiteln�m (nastavit pr�va pro spou�t�n�), a pak jednodu�e napsat script.php vypis_tohle nebo script.php -h. Na Windows mus�te pro tento �kol vytvo�it d�vkov� soubor:

P��klad 25-2. D�vkov� soubor pro spou�t�n� PHP skriptu z p��kazov� ��dky (script.bat)

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

Za p�edpokladu, �e jste v��e uveden� program nazvali script.php a soubor php.exe m�te ulo�en� jako c:\php\php.exe, m��ete tento d�vkov� soubor spou�t�t takto: script.bat echothis nebo script.bat -h.

Viz tak� dokumentaci roz���en� Readline, kde najdete v�ce funkc� pro pou�it� k aplikac�m PHP spou�t�n�ch z p��kazov� ��dky.



add a note add a note User Contributed Notes
Pou�it� PHP z p��kazov� ��dky
david at acz dot org
23-Sep-2004 07:46
If you want an interactive command line shell for PHP to test out code, give phpa a try:

fabio at soi dot city dot ac dot uk
24-Aug-2004 05:06
This might seem obvious to many, but infact limits a lots the possibility of reusing software that runs on a web server.
In the command line version of PHP you cannot use session variables (because they exploit cookies). It appears that I cannot even read the $GLOBALS array.

Fabio
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_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 smth

<?
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!
chris at free-source dot com
20-Jan-2003 10:23
The php binary that come with Mandrake (tested with 7.2, 8.2, 9.0) seems to not support -r <code>.  -r is not listed when running php -h and it gives you the -h if you try to use -r.
stuartc1 at hotmail dot com
13-Jan-2003 06:18
If you have an older version of PHP (for example 4.1.2 as I have have), and trying to execute a script from the windows NT command line then try this:

>c:\php\php -q c:\file_to_execute.php

note that you may need to execute from withing your php.exe directory as above. remeber to put the full path to the script you want to execute. The -q means quite mode and suppressed headers, you could also try -f or with no switches at all.
limberg at nospam dot grebmil dot port5 dot com
10-Jan-2003 11:39
The manual keeps referring to c:\php\cli\php.exe for windows.  I have no "cli" directory so I just tried c:\php\php.exe in my .bat file.  Not sure what the difference is but it seems to work fine on Win98 SE without any server installed or running.  Just though it might help someone.
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:

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.
vboctor at hotmail dot com
27-Jun-2002 10:52
You will only be able to use $argc and $argv if you have in php.ini:
register_globals = On
register_argc_argv = On

If you have register_globals = Off, then you should use $_SERVER['argc'] and $_SERVER['argv'][0]. (recommended approach)

Also for some reason php "-c /my/path/php.ini" did not work for me.  I had to use "php -c /my/path/" which looks for php.ini in the specified path.  This is for PHP 4.2.1 (compiled under FreeBSD).
daveATtechweaversDOTnet
14-Jun-2002 07:46
a few missing d's in the handy function. here it is with the typos fixed

<?php
if (version_compare(phpversion(),'4.3.0','<'))
       {
      
define('STDIN',fopen("php://stdin","r"));
      
define('STDOUT',fopen("php://stdout","r"));
      
define('STDERR',fopen("php://stderr","r"));
      
register_shutdown_function( create_function( '' , 'fclose(STDIN);
       fclose(STDOUT); fclose(STDERR); return true;'
) );
       }
?>
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(STOUT); fclose(STERR); return true;' ) );
   }

/* get some STDIN up to 256 bytes */
  
$str = fgets(STDIN,256);
?>
ashley at dcs dot warwick dot ac dot uk
02-Apr-2002 09:05
If $argc and $argv seem to be undefined variables, check the settings of both register_globals and register_argc_argv in php.ini.
philip at cornado dot com
28-Feb-2002 10:53
PHP comes standard with a CLI (binary) as of 4.2.0+
philip at cornado dot com
25-Feb-2002 10:02
See also:
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.
atomlinson at austin dot rr dot com
24-Jan-2002 06:28
To build the php exuecutable, you must run
configure *without* the '--with-apxs' option.
That option causes 'make' to build an apache
module.  I built php twice, once with '--with-apxs'
to build the apache module, and once without.
After compiling without, I copied the file 'php'
to a system bin directory (e.g., '/usr/local/bin').
temposeb at wanadoo dot fr
17-Nov-2001 07:32
Petite astuce pour saisir des donn�es au clavier lors de l'ex�cution d'un script (en mode console), on passe par un fichier :

$clavier = fopen('CON', 'r') ; //*** ou '/dev/tty' sous Linux
$s = fgets($clavier, 1024) ;
$s = chomp($s) ;
print("Vous avez saisi '$s'\n") ;
fclose($clavier) ;

S�b.

<Bezpe�n� re�imReference funkc�>
 Last updated: Thu, 15 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Sun Nov 14 23:09:54 2004 Local time zone must be set--see zic manual page