Home > Computer, PHP > Passing Values from the Commandline to PHP by GET/POST Method

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

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: , , ,
  1. December 20, 2014 at 12:50 am

    Hi,
    Im using php command in cron tasks to call wp_cron.php but i cannot run this file as wp_cron.php?doing_wp_cron because i get an error file not fould. Can you please tell me how can i do it with second method?

    Thanks you
    George

    • December 20, 2014 at 10:57 am

      The above method does *not* allow to pass parameters on the commandline in a GET-style, so you cannot run a script from the commandline (or cron) by typing php myscript.php?param1=value1&param2=value2. This will simply result in a file-not-found exception, since no file of this name exists.

      So, is wp_cron.php your own file, and you can modify it?

      If yes, then the trivial solution is to simply call it by php myscript.php value1 value2 from the commandline (or cron), and read all passed parameter values from within your php-script by $value1 = $argv[1]; $value2 = $argv[2]; ....

      Only if your php-script already refers to $_GET[...] at multiple positions, and you do not want to change all these positions to $argv[...], then you can simply use one of the methods described in my blog post.

      For example, the first method would then lead to calling php myscript.php 'param1=value1&param2=value2' from the commandline (or cron), so you only have to add lines 2-5 to your existing wp_cron.php file.

      For the second method you have to create another file called wrap.php, and then run php wrap.php 'myscript.php?param1=value2&param2=value2&...' from the commandline (or cron). (Of course, you might have to specify the full path to wrap.php).

      • December 20, 2014 at 12:09 pm

        Thank you for the quick reply.
        wp-cron.php is my own file and i can modify it. its in the root of a wordpress website.
        Code of file can be found at https://github.com/WordPress/WordPress/blob/master/wp-cron.php
        From line 60 to 71 there is a code like :

        // Use global $doing_wp_cron lock otherwise use the GET lock. If no lock, trying grabbing a new lock.
        if ( empty( $doing_wp_cron ) ) {
        if ( empty( $_GET[ ‘doing_wp_cron’ ] ) ) {
        // Called from external script/job. Try setting a lock.
        if ( $doing_cron_transient && ( $doing_cron_transient + WP_CRON_LOCK_TIMEOUT > $gmt_time ) )
        return;
        $doing_cron_transient = $doing_wp_cron = sprintf( ‘%.22F’, microtime( true ) );
        set_transient( ‘doing_cron’, $doing_wp_cron );
        } else {
        $doing_wp_cron = $_GET[ ‘doing_wp_cron’ ];
        }
        }

        I dont understand how to do it with method 2.

        Do i create a new file called wrap.php with code :

        and then create a cron task like php wrap.php ‘path/wp-cron.php?doing_wp_cron=doing_wp_cron’ ???

        Thank you

        • December 20, 2014 at 12:34 pm

          Exactly. This should work, so try it out!

          The full command would be something like
          php [path1]wrap.php '[path2]wp-cron.php?doing_wp_cron=XXX',
          where [path1] can be omitted if you run this command from the commandline in the same directory as wrap.php, but you should specifiy it in the crontab, since cronjobs have their current directory set to some other system directory.
          Further, [path2] is passed to the include-command within wrap.php, so it can either be an absolute path, or a path relative from wrap.php to wp-cron.php. In particular, if both php-files lie in the same directory, [path2] can simply be empty.
          Finally, the value XXX must be set to the value that you want to assign to the variable named doing_wp_cron, so this depends on the wordpress-internals. As far as I can see, you want to pass some value that finally evaluates to empty(value) == TRUE? Then you could omit XXX (that is, assign the empty string), or set it explicitly to value 0. If it should have some other specific value, then set XXX to this value (but I suppose that assigning doing_wp_cron=doing_wp_cron is not intended).
          Finally, note that you have to use single vertical quotes in the command, which you might leave out if there are no spaces contained between them. So, the following should do the trick:
          php [path1]wrap.php [path2]wp-cron.php?doing_wp_cron=

  2. Reimond
    January 28, 2015 at 9:13 am

    Thanks to the author for the code snippets and to google for locating this, saved a lot of working time!

  3. January 13, 2017 at 10:20 am

    где купить дженерик купить в москве дженерики виагра сиалис левитра дженерик виагры купить в аптеке Купить дженерики купить дженерик виагра сиалис купить дженерики с доставкой софосбувир дженерик купить купить дешевые дженерики

    http://stoyak.men

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: