How to pass GET variables to php file with Shell?

2019-05-10 03:19发布

Possible Duplicate:
PHP passing $_GET in linux command prompt

i want execute php file with Shell script but i dont know how i can pass GET variables.

This script "php script.php?var=data" don't work because Shell can't find the file "script.php?var=data".

So ,do you know how i can pass my variables ? If it's really impossible to use GET variable, can i pass variables by an other way and use it in my php script ?

标签: php shell
3条回答
别忘想泡老子
2楼-- · 2019-05-10 03:36

PHP CLI takes variables within a command structure like:

php woop.php --path=/home/meow/cat.avi

You can then use something like http://php.net/manual/en/function.getopt.php to get that option like so in your PHP script:

getopt('path')

Or you can get them directly form argv.

As an alternative as @GBD says you can use a bash script to wget a page of your site as well.

查看更多
一纸荒年 Trace。
3楼-- · 2019-05-10 03:50

My idea would be to write some kind of wrapper script to feed to /usr/bin/php and give that a string of arguments to grab the data from. Make no mistake, it is a hack and probably not a good one at that, but it should get the job done.

<?php
/** Wrapper.php
 **
 ** Description: Adds the $_GET hash to a shell-ran PHP script
 **
 ** Usage:       $ php Wrapper.php <yourscript.php> arg1=val1 arg2=val2 ...
**/

//Grab the filenames from the argument list
$scriptWrapperFilename = array_shift($argv); // argv[0]
$scriptToRunFilename = array_shift($argv); // argv[1]

// Set some restrictions
if (php_sapi_name() !== "cli")
    die(" * This should only be ran from the shell prompt!\n");

// define the $_GET hash in global scope
$_GET;

// walk the rest and pack the $_GET hash
foreach ($argv as $arg) {
    // drop the argument if it's not a key/val pair
    if(strpos($arg, "=") === false)
        continue;

    list($key, $value) = split("=", $arg);

    // pack the $_GET variable
    $_GET[$key] = $arg;
}

// get and require the PHP file we're trying to run
if (is_file($scriptToRunFilename))
    require_once $scriptToRunFilename;
else
    die(" * Could not open `$scriptToRunFilename' for inclusion.\n");

?>
查看更多
你好瞎i
4楼-- · 2019-05-10 03:52

If you're executing your script via the command-line (such as php your_script.php), you will not be able to use the $_GET parameters, as you're experiencing.

However, you can make use of PHP's CLI which graciously gives you the $argv array.

To use it, you will call your script like this:

php your_script.php variable1 "variable #2"

Inside your script, you can access the variables with:

<?php

$variable1 = $argv[1];
$variable2 = $argv[2];

?>
查看更多
登录 后发表回答