sep16 at psu dot edu ¶
10 years ago
You can easily parse command line arguments into the $_GET variable by using the parse_str[] function.
$ 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.
It behaves exactly like you'd expect with cgi-php.
Anonymous ¶
1 year ago
We can pass many arguments directly into the hashbang line.
As example many ini setting via the -d parameter of php.
---
#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
phpinfo[];
exit;
---
./script | grep memory
memory_limit => 2048M => 2048M
---
But we can also use this behaviour into a second script, so it call the first as an interpreter, via the hashbang:
---
#!./script arg1 arg2 arg3
---
However the parameters are dispatched in a different way into $argv
All the parameters are in $argv[1], $argv[0] is the interpreter script name, and $argv[1] is the caller script name.
To get back the parameters into $argv, we can simply test if $argv[1] contains spaces, and then dispatch again as normal:
#!/usr/bin/php -d memory_limit=2048M -d post_max_size=0
---
array[3] {
[0]=>
string[8] "./script"
[1]=>
string[15] "arg1 arg2 arg3 "
[2]=>
string[14] "./other_script"
}
array[4] {
[0]=>
string[8] "./other_script"
[1]=>
string[4] "arg1"
[2]=>
string[4] "arg2"
[3]=>
string[4] "arg3"
}
---
This will maintain the same behaviour in all cases and allow to even double click a script to call both parameters of another script, and even make a full interpreter language layer. The other script doesn't has to be php. Take care of paths.
apmuthu at usa dot net ¶
4 years ago
Adding a pause[] function to PHP waiting for any user input returning it:
frankNospamwanted at. toppoint dot. de ¶
7 years ago
Parsing commandline argument GET String without changing the PHP script [linux shell]:
URL: index.php?a=1&b=2
Result: output.html
echo "" | php -R 'include["index.php"];' -B 'parse_str[$argv[1], $_GET];' 'a=1&b=2' >output.html
[no need to change php.ini]
You can put this
echo "" | php -R 'include["'$1'"];' -B 'parse_str[$argv[1], $_GET];' "$2"
in a bash script "php_get" to use it like this:
php_get index.php 'a=1&b=2' >output.html
or directed to text browser...
php_get index.php 'a=1&b=2' |w3m -T text/html
drewish at katherinehouse dot com ¶
17 years ago
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']];"
lucas dot vasconcelos at gmail dot com ¶
15 years ago
Just another variant of previous script that group arguments doesn't starts with '-' or '--'
$ 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
]
ohcc at 163 dot com ¶
6 years ago
use " instead of ' on windows when using the cli version with -r
php -r "echo 1"
-- correct
php -r 'echo 1'
PHP Parse error: syntax error, unexpected ''echo' [T_ENCAPSED_AND_WHITESPACE], expecting end of file in Command line code on line 1
sam marshall ¶
3 years ago
When using the -R flag, the name of the variable containing the content of the current line [not including the LF] is $argn.
For example you can do this code:
cat file.txt | php -R 'echo $argn . "\n";'
This will just output each line of the input file without doing anything to it.
PSIKYO at mail dot dlut dot edu dot cn ¶
9 years ago
If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:
[root@ItsCloud02 wsdl]# ./lnxcli.php
Extension './lnxcli.php' not present.
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.
notreallyanaddress at somerandomaddr dot com ¶
12 years ago
If you want to be interactive with the user and accept user input, all you need to do is read from stdin.
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!
pyxl at jerrell dot com ¶
20 years ago
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.
losbrutos at free dot fr ¶
15 years ago
an another "another variant" :
$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
]
jeff at noSpam[] dot genhex dot net ¶
20 years ago
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.
linn at backendmedia dot com ¶
18 years ago
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.
stromdotcom at hotmail dot com ¶
16 years ago
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, "", 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 //www.stromcode.com
Popeye at P-t-B dot com ¶
19 years ago
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.
Alexander Plakidin ¶
19 years ago
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
docey ¶
17 years ago
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.
james_s2010 at NOSPAM dot hotmail dot com ¶
14 years ago
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
Hope this helps someone.
djcassis at gmail ¶
15 years ago
To display colored text when it is actually supported :
To reset these settings :
More fun :
More info here : //www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html