22

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

Browser version: script.php?var=3

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

5 Answers 5

41

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
6

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.

Comments

6

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

E.g.:

var = 3 php -f test.php

In test.php:

$var = getenv("var");

Comments

4

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.

Comments

4

A lot of solutions put the arguments into variables according to their order. For example,

myfile.php 5 7

will put the 5 into the first variable and 7 into the next variable.

I wanted named arguments:

myfile.php  a=1 x=8

so that I can use them as variable names in the PHP code.

The link that Ionuț G. Stan gave at http://www.php.net/manual/en/features.commandline.php

gave me the answer.

sep16 at psu dot edu:

You can easily parse command line arguments into the $_GET variable by using the parse_str() function.

<?php
parse_str(implode('&', array_slice($argv, 1)), $_GET);
?>

It behaves exactly like you'd expect with cgi-php.

$ php -f somefile.php a=1 b[]=2 b[]=3

This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').

1 Comment

IMPORTANT: Must use if (PHP_SAPI === 'cli') before of parse_str function, because does not overwrite $_GET when use on web.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.