Sobes.tech
Junior — Middle

Is it possible in PHP to model and save a list of parameters from a GET request into an array when running the script via the command line?

sobes.tech AI

Answer from AI

In PHP, when running a script from the command line (CLI), the $_GET variable is not populated by default because there is no HTTP request. However, you can simulate GET parameters by passing them through command line arguments and then parsing them into an array.

Example:

<?php
// Get command line arguments
parse_str($argv[1] ?? '', $_GET);

// Now $_GET contains the parameters, for example:
print_r($_GET);

Run from the console:

php script.php "param1=value1&param2=value2"

As a result, $_GET will be:

Array
(
    [param1] => value1
    [param2] => value2
)

Thus, you can emulate GET parameters in the CLI environment.