User Contributed Notes 54 notes

You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

It behaves exactly like you'd expect with cgi-php.

$ php -f somefile.php a=1 b[]=2 b[]=3

This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

Even better, instead of putting that line in every file, take advantage of PHP's auto_prepend_file directive. Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:

auto_prepend_file = "/etc/php/cli-php5.3/local.prepend.php"

It will be automatically prepended to any PHP file run from the command line.

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

// 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 endHANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;

Using CLI (on WIN at least), some INI paths are relative to the current working directory. For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there. Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.

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.

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

i use emacs in c-mode for editing. in 4.3, starting a cli script like so:

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

told emacs to drop into c-mode automatically when i loaded the file for editing. the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.

in 5.2, '-q' has apparently been deprecated. replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:

#!/usr/bin/php -- /* -*- c -*- */<?php

don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...

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:

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:

dunno if this is on linux the same but on windows evertimeyou send somthing to the console screen php is waiting forthe 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.

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 anapp that is outputting a lot to the console, i.e. a textbased screen with frequent updates, then its much better to first cach all output, and output is as one big chunk oftext instead of one char a the time.

ouput buffering is ideal for this. in my script i outputtedalmost 4000chars of info and just by caching it first, itspeeded up by almost 400% and dropped cpu-usage.

because what is being displayed doesn't matter, be it 2chars 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-basedsystems. it seems that the STDOUT stream just waits for the console to report ready, before continueing execution.

Or you may encounter some other strange problem.Care the enter key. In windows environment, enter key generate two binary characters '0D0A'. But in Linux, enter key generate just only a 'OA'.I wish it can help someone if you are using windows to code php and run it as a command line program on linux.

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.

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!

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.

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.

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.

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 ).

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.

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.iniIf you want MySQL support in the CLI, make sure the line extension=mysql.sois 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.

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.

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!

I had problems running php as CGI in thttpd. I have followed instructions posted by db at digitalmediacreation dot ch, but I was still getting "500 Internal Error" answer from the server. However, I had no problems running php as CLI using a simple wrapper file named index.cgi:

#!/usr/bin/php<?phprequire_once 'index.php';?>

but i needed to pass user data through GET and POST, and this method couldn't handle it. I have spent 2 hours figuring out how to run the CGI mode properly, until I finally gave up, and done it in "manual" way. I have just added some code to the wrapper that reads GET and POST data into the proper variables:

#!/usr/bin/php<?php

//parse the command line into the $_GET variableparse_str($_SERVER['QUERY_STRING'], $_GET);