tags:

views:

149

answers:

4

I have a PHP script named "scipt" and a textfile called 'data.txt'. Right now I can execute script, but then I need to type in "data.txt". Is there any way to pass in data.txt as a parameter to "script" so I can run this thing in one line automated?

Right now I'm typing:

php script {enter} // script runs and waits for me to type filename
data.txt {enter}
... executes

Ideally it would look like:

php script data.txt {enter}
...executes

I'm doing this all from the PHP command line. Cheers :)

+1  A: 

Arguments to your script will be available in $argv

timdev
+3  A: 
 mscharley@S04:~$ cat test.php
<?php
var_dump($_SERVER['argc']);
var_dump($_SERVER['argv']);
?>
 mscharley@S04:~$ php test.php foo bar
int(3)
array(3) {
  [0]=>
  string(8) "test.php"
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
}
 mscharley@S04:~$
Matthew Scharley
A: 

Or $_SERVER['argv'] (which doesn't require register_globals being turned on) - however, both solutions DO require having register_argc_argv turned on. See the documentation for details.

TML
From the command line, argv/argc are available regardless of register_argc_argv, since 4.3.0. See: http://docs.php.net/manual/en/features.commandline.php
timdev
or this:http://us2.php.net/manual/en/reserved.variables.argv.php
txyoji
That's not 100% true. That's merely the DEFAULT value compiled into the SAPI - this can be overridden via php.ini or command-line arguments. e.g.:/tmp $ cat x<?php var_dump($_SERVER['argv']);/tmp $ php -d register_argc_argv=0 -f x a b cNULLAlso, it assumes that the CLI SAPI is in use, rather than the CGI SAPI (it's quite common to find people using the CGI SAPI as a 'CLI' solution due to distro preferences for paths)
TML
A: 

If you actually need the file, you can get the file name by using the $argv variable. That would allow you to run it like

php script data.txt

Then "data.txt" will be $argv[1] ($argv[0] is the script name itself).

If you don't actually need the file, but only its content. You can process standard input (STDIN) using any of the normal stream reading functions (stream_get_contents(), fread() etc...). This allows you to direct standard input like so:

php script << data.txt

This is a common paradigm for *nix-style utilities.

Brenton Alker