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

Just pass it as normal parameters and access it in PHP using the $argv array.

php myfile.php daily

and in myfile.php

$type = $argv[1];
查看更多
迷人小祖宗
3楼-- · 2019-01-05 00:38

These lines will convert the arguments of a CLI call like php myfile.php "type=daily&foo=bar" into the well known $_GET-array:

if (!empty($argv[1])) {
  parse_str($argv[1], $_GET);
}

Though it is rather messy to overwrite the global $_GET-array, it converts all your scripts quickly to accept CLI arguments.

See http://php.net/manual/en/function.parse-str.php for details.

查看更多
家丑人穷心不美
4楼-- · 2019-01-05 00:38

Save this code in file myfile.php and run as php myfile.php type=daily

<?php
$a = $argv;
$b = array();
if (count($a) == 1) exit;
foreach ($a as $key => $arg){
        if ($key > 0){
            list($x,$y) = explode('=', $arg);
            $b["$x"]    = $y;  
           }
       }
?>

If you add var_dump($b); before the ?> tag, you will see that the array $b contains type => daily.

查看更多
虎瘦雄心在
5楼-- · 2019-01-05 00:40

The ?type=daily argument (ending up in the $_GET array) is only valid for web-accessed pages.

You'll need to call it like php myfile.php daily and retrieve that argument from the $argv array (which would be $argv[1], since $argv[0] would be myfile.php).

If the page is used as a webpage as well, there are two options you could consider. Either accessing it with a shell script and wget and call that from cron:

#!/bin/sh
wget http://location.to/myfile.php?type=daily

Or check in the php file whether it's called from the commandline or not:

if (defined('STDIN')) {
  $type = $argv[1];
} else { 
  $type = $_GET['type'];
}

(Note: You'll probably need/want to check if $argv actually contains enough variables and such)

查看更多
ら.Afraid
6楼-- · 2019-01-05 00:43

You could use what sep16 on php.net recommends:

<?php

parse_str(implode('&', array_slice($argv, 1)), $_GET);

?>

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

$ php -f myfile.php type=daily a=1 b[]=2 b[]=3

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

查看更多
We Are One
7楼-- · 2019-01-05 00:44

Just pass it as parameters as follows:

php test.php one two three

and inside test.php:

<?php
if(isset($argv))
{
    foreach ($argv as $arg) 
    {
        echo $arg;
        echo "\r\n";
    }
}
?>
查看更多
登录 后发表回答