Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass parameters from the command line to $_POST in a PHP script?

I know this could sound a little weird, but I need to pass some parameters to the $_POST array. Similar to the way Apache does it, or any other web server.

Unfortunately I couldn't find libapache2-mod-php5 anywhere for my Ubuntu installation.

like image 685
hades Avatar asked Apr 13 '11 20:04

hades


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 write command line script in PHP?

Yes, we can create a command-line PHP script as we do for web script, but with few little tweaks. We won't be using any kind of HTML tags in command-line scripting, as the output is not going to be rendered in a web browser, but displayed in the DOS prompt / Shell prompt.

What is PHP command line?

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.


1 Answers

Just insert the following lines at the beginning of your script:

/* If started from the command line, wrap parameters to $_POST and $_GET */ if (!isset($_SERVER["HTTP_HOST"])) {   parse_str($argv[1], $_GET);   parse_str($argv[1], $_POST); } 

This small piece of code does the trick (you may decide if you want to use $_GET or $_POST or, like I needed it, both.

After changing your script, you can call it from the command line passing your arguments:

php yourscript.php 'arg1=x&arg2=y' 
like image 134
Schlangi Avatar answered Oct 05 '22 11:10

Schlangi