Pass variable to php script running from command l

2019-01-04 23:50发布

I have a PHP file that is needed to be run from command line (via crontab). I need to pass type=daily to the file but I don't know how. I tried:

php myfile.php?type=daily

but this error was returned:

Could not open input file: myfile.php?type=daily

What can I do?

12条回答
劳资没心,怎么记你
2楼-- · 2019-01-05 00:26
<?php
if (count($argv) == 0) exit;
foreach ($argv as $arg)
echo $arg;
?>

This code should not be used. First of all CLI called like: /usr/bin/php phpscript.php will have one argv value which is name of script

array(2) {
   [0]=>
   string(13) "phpscript.php"
}

This one will always execute since will have 1 or 2 args passe

查看更多
成全新的幸福
3楼-- · 2019-01-05 00:27

To use $_GET so you dont need to support both if it could be used from command line and from web browser.

if(isset($argv))
    foreach ($argv as $arg) {
        $e=explode("=",$arg);
        if(count($e)==2)
            $_GET[$e[0]]=$e[1];
        else    
            $_GET[$e[0]]=0;
    }
查看更多
混吃等死
4楼-- · 2019-01-05 00:28

Using getopt() function we can also read parameter from command line just pass value with php running command

php abc.php --name=xyz

abc.php

$val = getopt(null, ["name:"]);
print_r($val);
o/p:-
array ( 'name' => 'xyz', )

查看更多
霸刀☆藐视天下
5楼-- · 2019-01-05 00:29
if (isset($argv) && is_array($argv)) {
    $param = array();
    for ($x=1; $x<sizeof($argv);$x++) {
        $pattern = '#\/(.+)=(.+)#i';
        if (preg_match($pattern, $argv[$x])) {
            $key =  preg_replace($pattern, '$1', $argv[$x]); 
            $val =  preg_replace($pattern, '$2', $argv[$x]);
            $_REQUEST[$key] = $val;
            $$key = $val;
        }    
    }
}

I put parameters in $_REQUEST

$_REQUEST[$key] = $val;

and also usable directly

$$key=$val

use this like that:

myFile.php /key=val

查看更多
Melony?
6楼-- · 2019-01-05 00:30

parameters send by index like other application

php myfile.php type=daily

and then you can gat them like this

<?php
if (count($argv) == 0) exit;
foreach ($argv as $arg)
    echo $arg;
?>
查看更多
甜甜的少女心
7楼-- · 2019-01-05 00:33

I strongly recommend the use of getopt.

Documentation at http://php.net/manual/en/function.getopt.php

If you wanna the help print out for your options than take a look at https://github.com/c9s/GetOptionKit#general-command-interface

查看更多
登录 后发表回答