For different reasons, I encounter this problem every year and kept forgetting how to solve this. So I thought I would write this solution as a blog so I always remember. :)
First of all, the answer to the question is you cannot. Why?
Because $_GET and $_POST (and a few others) are HTTP variables. Meaning they can only be accessed if you are running the PHP file behind a web server. If you are trying to run a PHP file via CLI(command Line Interface), you'll not get those $_GET and $_POST variables.
First of all, the answer to the question is you cannot. Why?
Because $_GET and $_POST (and a few others) are HTTP variables. Meaning they can only be accessed if you are running the PHP file behind a web server. If you are trying to run a PHP file via CLI(command Line Interface), you'll not get those $_GET and $_POST variables.
But all is not lost. There is a work around to handle that problem and that is to use $argc and $argv variables.
$argc is the number of parameters passed in the command line while $argv holds the actual parameters stored in a zero based index array.
Example:
[ian@mycomputer]$ /usr/bin/php myscript.php hello world
$argc value will be 3. $argv will be an array of 3 strings containing "myscript.php", "hello" and "world."
Now back to our problem. To solve it, we will be using $argc and $argv to fill up the $_GET or $_POST variable. How?
Using a browser, to fill up the $_GET variable, you add the data by appending text to the URL.
Example:
http://test.com/myscript.php?name=ian&age=16
$_GET variable will contain the index 'name' with value 'ian' and index 'age' with value '16'.
To get the same thing using CLI, we use the following code:
function ArgsToGet($argv)
{
$gets = explode('&', $argv[1]);
foreach($gets as $g)
{
$g = explode('=', $g);
$_GET[$g[0]] = $g[1];
}
}
var_dump($argv);
ArgsToGet($argv);
var_dump($_GET);
?>
Example:
[ian@mycomputer]$ /usr/bin/php myscript.php 'name=ian&age=16'
Using the code above, the command will output will be
array(2) {
[0]=>
string(8) "test.php"
[1]=>
string(15) "name=ian&age=16"
}
array(2) {
["name"]=>
string(3) "ian"
["age"]=>
string(2) "16"
}
The variable $_GET will have the values same as it was when using a browser.
Comments
blog comments powered by Disqus