Run php script from command line with variable

2019-02-11 16:43发布

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条回答
萌系小妹纸
2楼-- · 2019-02-11 16:54

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.

查看更多
Viruses.
3楼-- · 2019-02-11 17:09

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

E.g.:

var = 3 php -f test.php

In test.php:

$var = getenv("var");
查看更多
对你真心纯属浪费
4楼-- · 2019-02-11 17:10

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.

查看更多
倾城 Initia
5楼-- · 2019-02-11 17:14

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').

查看更多
6楼-- · 2019-02-11 17:18

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.

查看更多
登录 后发表回答