PHP Passing $_Get in the Linux Command Prompt

PHP passing $_GET in the Linux command prompt

Typically, for passing arguments to a command line script, you will use either the argv global variable or getopt:

// Bash command:
// php -e myscript.php hello
echo $argv[1]; // Prints "hello"

// Bash command:
// php -e myscript.php -f=world
$opts = getopt('f:');
echo $opts['f']; // Prints "world"

$_GET refers to the HTTP GET method parameters, which are unavailable on the command line, since they require a web server to populate.

If you really want to populate $_GET anyway, you can do this:

// Bash command:
// export QUERY_STRING="var=value&arg=value" ; php -e myscript.php
parse_str($_SERVER['QUERY_STRING'], $_GET);
print_r($_GET);
/* Outputs:
Array(
[var] => value
[arg] => value
)
*/

You can also execute a given script, populate $_GET from the command line, without having to modify said script:

export QUERY_STRING="var=value&arg=value" ; \
php -e -r 'parse_str($_SERVER["QUERY_STRING"], $_GET); include "index.php";'

Note that you can do the same with $_POST and $_COOKIE as well.

Replacing $_GET to make it work from command line

Change

$d = $_GET['domain'];

to:

$d = $argv[1];

...and call it at the command line like this:

php /path/to/script.php "www.domaintocheck.com"

Can I pass $_GET parameters to a script running locally?

You can't do this that way. Use argv and argc. See Command Line Usage section in manual

URL parameters when running PHP via CLI

There are two special variables in every command line interface argc and argv.

argv - array of arguments passed to the script.

argc - the number of command line parameters passed to the script (if run on the command line).

Make script cli.php

<?php
print_r($_SERVER['argv']);

and call it with argument:

$ php cli.php argument1=1

You should get the output looking like:

Array
(
[0] => cli.php
[1] => argument1=1
)

Source: http://www.php.net/manual/en/reserved.variables.server.php

If you are still so demanding to have a single point entry and to be able to process the url query as $_GET make your script act like a router by adding a switch:

if (PHP_SAPI === 'cli')
{
// ... BUILD $_GET array from argv[0]
}

But then - it violates SRP - Single Responsibility Principle! Having that in mind if you're still so demanding to make it work like you stated in the question you can do it like:

if (PHP_SAPI === 'cli')
{
/** ... BUILD from argv[0], by parsing the query string, a new array and
* name it $data or at will
*/
}
else
{
// ... BUILD new $data array from $_GET array
}

After that convert the code to use $data array instead of $_GET

...and have a nice day!



Related Topics



Leave a reply



Submit