views:

700

answers:

4

I want to run a php script from the command line, but I also want to set a variable for that script ie.

Browser version: script.php?var=3

Command line: php -f script.php (but how do I give it the variable?)

PS. doesn't matter if it's a GET variable or not, I just used that as an example.

+10  A: 

Script:

<?php

// number of arguments passed to the script
var_dump($argc);

// the arguments as an array. first argument is always the script name
var_dump($argv);

Command:

$ php -f test.php foo bar baz
int(4)
array(4) {
  [0]=>
  string(8) "test.php"
  [1]=>
  string(3) "foo"
  [2]=>
  string(3) "bar"
  [3]=>
  string(3) "baz"
}

Also, take a look at using PHP from the command line.

Ionuț G. Stan
works fine... other answers would work too but this was first and does make it look better than having a long list of variable names and data.
Hintswen
+3  A: 

As well as using argc and argv as indicated by Ionut G. Stan, you could also use the PEAR module Console_Getopt which can parse out unix-style command line options. See this article for more information.

Alternatively, there's similar functionality in the Zend Framework in the Zend_Console_Getopt class.

Paul Dixon
+1  A: 

Besides argv (as Ionut mentioned), you can use environment variables:

E.g.:

var = 3 php -f test.php

In test.php:

$var = getenv("var");
Matthew Flaschen
+1  A: 

If you want to keep named parameters almost like var=3&foo=bar (instead of the positional parameters offered by $argv) getopt() can assist you.

VolkerK