skcubrats
skcubrats

Reputation:

How to pass file into PHP CLI?

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

Upvotes: 2

Views: 3453

Answers (4)

Brenton Alker
Brenton Alker

Reputation: 9072

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 $argv1 ($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.

Upvotes: 0

TML
TML

Reputation: 12966

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.

Upvotes: 0

Matthew Scharley
Matthew Scharley

Reputation: 132374

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

Upvotes: 3

timdev
timdev

Reputation: 62894

Arguments to your script will be available in $argv

Upvotes: 1

Related Questions