Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send request parameters when calling a PHP script via command line

When you run a PHP script through a browser it looks something like

http://somewebsite.com/yourscript?param1=val1&param2=val2.

I am trying to achieve the same thing via command line without having to rewrite the script to accept argv instead of $_REQUEST. Is there a way to do something like this:

php yourscript.php?param1=val1&param2=val2 

such that the parameters you send show up in the $_REQUEST variable?

like image 221
emilyk Avatar asked Jun 20 '13 15:06

emilyk


People also ask

How do I pass a command line argument to a PHP script?

To pass command line arguments to the script, we simply put them right after the script name like so... Note that the 0th argument is the name of the PHP script that is run. The rest of the array are the values passed in on the command line. The values are accessed via the $argv array.

Can we use PHP for command line scripts?

As of version 4.3. 0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP.

What is PHP CLI command?

PHP's Command Line Interface (CLI) allows you to execute PHP scripts when logged in to your server through SSH. ServerPilot installs multiple versions of PHP on your server so there are multiple PHP executables available to run.


2 Answers

I can't take credit for this but I adopted this in my bootstrap file:

// Concatenate and parse string into $_REQUEST
if (php_sapi_name() === 'cli') {
    parse_str(implode('&', array_slice($argv, 1)), $_REQUEST);
}

Upon executing a PHP file from the command line:

php yourscript.php param1=val1 param2=val2

The above will insert the keys and values into $_REQUEST for later retrieval.

like image 118
Robert Brisita Avatar answered Nov 15 '22 14:11

Robert Brisita


In case you don't want to modify running script, you can specify parameters using in -B parameter to specify code to run before the input file. But in this case you must also add -F tag to specify your input file:

php -B "\$_REQUEST = array('param1' => 'val1', 'param2' => 'val2');" -F yourscript.php
like image 37
Rage Steel Avatar answered Nov 15 '22 15:11

Rage Steel