2

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

4 Answers 4

3
 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:~$
Sign up to request clarification or add additional context in comments.

2 Comments

assuming the next step is file_get_contents...is file_get_contents($_SERVER['DOCUMENT_ROOT']."/".$argv[1]); the way to go? does it look in it's own directory by default (so file_get_contents($argv[1]); would be enough?) I don't have a command line version available, but need to build something that will be accessed that way. Thanks so much
nevermind...it's working now as I expected, something else must have been the problem
1

Arguments to your script will be available in $argv

Comments

0

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.

2 Comments

From the command line, argv/argc are available regardless of register_argc_argv, since 4.3.0. See: docs.php.net/manual/en/features.commandline.php
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 c NULL Also, 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)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.