Is it possible to pass an array as a command line argument to a PHP script?

前端 未结 9 868
忘掉有多难
忘掉有多难 2020-12-09 16:37

I\'m maintaining a PHP library that is responsible for fetching and storing incoming data (POST, GET, command line arguments, etc). I\'ve just fixed a bug that would not all

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-09 16:50

    After following the set of instructions below you can make a call like this:

    phpcl yourscript.php _GET='{ "key1": "val1", "key2": "val2" }'

    To get this working you need code to execute before the script being called. I use a bash shell on linux and in my .bashrc file I set the command line interface to make the php ini flag auto_prepend_file load my command line bootstrap file (this file should be found somewhere in your php_include_path):

    alias phpcl='php -d auto_prepend_file="system/bootstrap/command_line.php"'
    

    This means that each call from the command line will execute this file before running the script that you call. auto_prepend_file is a great way to bootstrap your system, I use it in my standard php.ini to set my final exception and error handlers at a system level. Setting this command line auto_prepend_file overrides my normal setting and I choose to just handle command line arguments so that I can set $_GET or $_POST. Here is the file I prepend:

     1)
    {
       $parsedArgs = array(); 
    
       for ($i = 1; $i < $argc; $i++)
       {
          parse_str($argv[$i], $parsedArgs[$i]);
       }
    
       foreach ($parsedArgs as $arg)
       {
          foreach ($arg as $key => $val)
          {
             // Set the global variable of name $key to the json decoded value.
             $$key = json_decode($val, true);
          }
       }
    
       unset($parsedArgs);
    }
    ?>
    

    It loops through all arguments passed and sets global variables using variable variables (note the $$). The manual page does say that variable variables doesn't work with superglobals, but it seems to work for me with $_GET (I'm guessing it works with POST too). I choose to pass the values in as JSON. The return value of json_decode will be NULL on error, you should do error checking on the decode if you need it.

提交回复
热议问题