Python script calling PHP script while passing $_GET parameters

php, python

Solution

Try the following with your Python passing in as many params as you'd like.

subprocess.call(["php","-f","test.php","param0:value0", "param1:value1"])

Now in PHP:

<?php
$_GET = array();

foreach($argv as $key => $pair) {
    if ($key == 0) { //skip first element which is script name (test.php)
        continue;
    }

    list($key, $value) = explode(":", $pair);
    $_GET[$key] = $value;
}

This manually parses `$argv` and populates `$_GET` for you so you only have modify the beginning of your PHP file.

This is an imperfect solution if your key or value have the same value as the `:` delimiter. An even better way would be to pass in the parameters via a JSON string. Something like:

subprocess.call(["php","-f","test.php", json.dumps(your_dictionary)])

and in PHP

<?php
if ($argc > 1) {
  $json_str = $argv[1];
  $_GET = json_decode($json_str);
}

and finally as suggested by user574632, you can wrap this code with the following `if` statment to ensure it doesn't interfere if you're still running it as a web-script as well.

if (php_sapi_name() == 'cli') {
  //execute in here *only* if run from the command-line
}

Problem

I'm currently using `subprocess.call(["php", "test.php"])` in my python script to call a PHP script. I would like to know if it's possible to pass `$_GET` parameters to the script while calling it. If it's possible how would I do it? This is what I'm trying to get: "`subprocess.call(["php", "test.php?i=3"])`" This is my current code: test.py ``` import subprocess subprocess.call(["php", "test.php"]) ``` test.php ``` <?php echo $_GET['i']; ?> ```

Original source

Related problems