How do I transfer a file to PHP CLI?

I have a PHP script named "scipt" and a text file called data.txt. Right now I can execute the script, but then I need to enter "data.txt". Is there a way to pass the "script" parameter to data.txt so that I can run this thing on one line automatically?

Now I am typing:

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

      

Ideally it would look like this:

PHP  data.txt {enter}
...executes

      

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

+2


source to share


4 answers


 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:~$

      



+3


source


Your script arguments will be available in $ argv



+1


source


Or $_SERVER['argv']

(which does not require inclusion register_globals

) - however, both DO solutions require inclusion register_argc_argv

. See the documentation for details .

0


source


If you really want the file, you can get the filename using the $ argv variable . This will allow you to run it like

PHP  data.txt

      

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

Unless you really need a file, just its contents. You can process standard input (STDIN) with any of the normal stream reading functions ( stream_get_contents () , fread () , etc.). This allows you to route standard input like this:

PHP  << data.txt

      

This is a common paradigm for utilities like nix.

0


source







All Articles