Archive

Archive for the ‘PHP’ Category

Passing Values from the Commandline to PHP by GET/POST Method

May 16, 2011 6 comments

When using the commandline tool php-cli to execute a php-script, it is not possible to pass values to the script in the same way as if they were passed by get or post via http. However, I just found some easy solution to solve this problem. By this method, you can test your script from the commandline with just a very small change to it. The second solution even allows you to use the script without any change at all.

Note that with php-cli it is possible to pass arguments to the global php array $argv using the syntax:

$ php myscript.php arg1 arg2 ...

From within the script you can access these arguments using:

$arg1 = $argv[1];
$arg2 = $argv[2];
...

You can make use of this feature in one of the following two ways.

1.) If you can modify the script you want to call:
Begin the script with:

<?php
  if (!isset($_SERVER["HTTP_HOST"])) {
    // script is not interpreted due to some call via http, so it must be called from the commandline
    parse_str($argv[1], $_GET); // use $_POST instead if you want to
  }

  // the rest of your script remains unchanged here...

Call it from the commandline by:

$ php myscript.php 'name1=value2&name2=value2&...'

2.) If you cannot modify the script you want to call:
Create the following wrapper-script and save it as ‘wrap.php’:

<?php
	$parts = explode("?", $argv[1], 2);
	if (count($parts) == 2)
		parse_str($parts[1], $_GET); // use $_POST instead if you want to

	include($parts[0]);
?>

Perform the following call from the commandline to start ‘myscript.php’ with custom parameters:

$ php wrap.php 'myscript.php?name1=value2&name2=value2&...'

Both alternatives do also support url-encoded values, e.g. using ‘name=one%20two’ instead of ‘name=one two’.

Advertisements
Categories: Computer, PHP Tags: , , ,