When calling a PHP script from the command line you can use $argc to find out how many parameters are passed and $argv to access them. For example running the following script:

<?php
    var_dump($argc); //number of arguments passed 
    var_dump($argv); //the arguments passed
?>

Like this:-

php script.php arg1 arg2 arg3

Will give the following output

int(4)
array(4) {
  [0]=>
  string(21) "d:\Scripts\script.php"
  [1]=>
  string(4) "arg1"
  [2]=>
  string(4) "arg2"
  [3]=>
  string(4) "arg3"
}

See $argv and $argc for further details.

To do what you want, lets say

php script.php arg1=4

You would need to explode the argument on the equals sign:-

list(val) = explode('=', $argv[1]);
var_dump(array(val));

That way you can have whatever you want in front of the equals sign without having to parse it, just check the key=>value pairs are correct. However, that is all a bit of a waste, just instruct the user on the correct order to pass the arguments.

Answer from vascowhite on Stack Overflow
🌐
PHP
php.net › manual › en › reserved.variables.argv.php
PHP: $argv - Manual
To use $_GET so you dont need to support both if it could be used from command line and from web browser. foreach ($argv as $arg) { $e=explode("=",$arg); if(count($e)==2) $_GET[$e[0]]=$e[1]; else $_GET[$e[0]]=0; } ... You can reinitialize the ...
🌐
Igor's Blog
igorkromin.net › index.php › 2017 › 12 › 07 › how-to-pass-parameters-to-your-php-script-via-the-command-line
How to pass parameters to your PHP script via the command line | Igor Kromin
December 7, 2017 - ?> To pass command line arguments to the script, we simply put them right after the script name like so... ... Argument #2 - value2 Note that the 0th argument is the name of the PHP script that is run.
🌐
Envato Tuts+
code.tutsplus.com › home › coding fundamentals
Get Command-Line Arguments With PHP $argv or getopt() | Envato Tuts+
December 19, 2021 - In this tutorial, you will learn how to access command-line arguments inside your script with $argv and getopt() in PHP. Arguments are passed around as query parameters when you request a page from your web browser.
🌐
A Star Trek Timeline
macs.hw.ac.uk › ~hwloidl › docs › PHP › features.commandline.html
Chapter 23. Using PHP from the command line
The number of arguments which can ... the script name (which is - in case the PHP code is coming from either standard input or from the command line switch -r)....
🌐
YouTube
youtube.com › watch
Code Sample: How to Pass Arguments to PHP CLI - YouTube
Did you know that you can execute PHP scripts in the command line interface? Here I show you a basic example of running command line scripts and passing argu...
Published   May 5, 2018
Find elsewhere
🌐
Team Treehouse
teamtreehouse.com › community › php-exec-function-passing-a-value-to-command-line
PHP exec function passing a value to command line (Example) | Treehouse Community
October 1, 2014 - Exec() method emulate the command line, meaning exec("example.php") works the same as php -f example.php on the command line. This means you can pass arguments to by putting a space between the file name and all the arguements (exactly like ...
🌐
Fixed Bugs
fixedbugs.io › php › how-to-pass-argument-to-command-line-in-php
How to pass arguments via command line to php | Fixed Bugs
PHP has a special variable, namely $argv that contains the arguments from Command Line. $argv is an array. By processing this array, you can get arguments by PHP script. The first element of the $argv array, $argv[0] is the script's filename.
🌐
SitePoint
sitepoint.com › php
Unable to pass command line arguments to PHP script - PHP - SitePoint Forums | Web Development & Design Community
September 11, 2017 - (Note: I’m new to PHP) I am trying to pass command line arguments to a PHP script on a Linux web server. I do not have access to the command line directly but I can run cron jobs OK which is how this needs to work. I can call PHP scripts from cron OK so that bit is OK but when I look at $argv I can’t see any arguments, I can’t even see anything in $argv[0] which should be the script name.
🌐
Webmaster World
webmasterworld.com › php › 4816138.htm
Passing variables to PHP running at the command line - PHP Server Side Scripting forum at WebmasterWorld - WebmasterWorld
I've tried to see what variables are present when the script runs which are _GET, _POST, _COOKIE, _FILES, argv, argc, and _SERVER, but looking at these arrays I don't see these fields being passed. I'm guessing I need to alter how the command is setup in order to send this data into the script. Does anyone have any direction on how I can achieve that? ... php /path/to/script.php arg1 arg2 arg3 You can access the values via $argv[1] etc.
🌐
Educative
educative.io › answers › what-are-command-line-arguments-in-php
What are command-line arguments in PHP?
Unlike other C-like languages, we don’t have to declare anything to handle command-line arguments because PHP itself comes with two built-in variables, $argv and $argc: $argv: an array of all the arguments passed to the script
🌐
Tom McFarlin
tommcfarlin.com › writing-php-command-line-applications-arguments
Writing PHP Command-Line Applications: Command-Line Arguments | Tom McFarlin
January 26, 2021 - And $argc is the number of arguments passed to the the script (which will always at least be 1). Arguably, pun intended, one of the key pieces of command-line application is making sure that they are interactive through command-line arguments. In PHP, there are two variables to understand:
Top answer
1 of 2
10

Arguments, made easy

One day I decided to defeat this monster once and for all. I forged a secret weapon - a function that acts as a storage, a parser and a query function for arguments.

    //  define your arguments with a multiline string, like this:

    arg('

            -q      --quiet-mode        bool        Suppress all error messages
            -f      --filename          str         Name of your input document
            -m      --max-lines         int         Maximum number of lines to read

    ');

    $argText = arg("??"); // removes bool/int/etc column
    print "
        Syntax:
            $argText
    
    ";

    //  then read any value like this:

    $maxLines = arg("max-lines",99);
    $filename = arg("filename");
    $stfuMode = arg("quiet-mode");


    //  let's see what we got

    printf("Value of --max-lines: %s\n",$maxLines);
    printf("Value of --quiet-mode: %s\n",$stfuMode);
    printf("Value of first unnamed argument: %s\n",arg(1));

Explanation

  • All you need to do is write the argument list as a multiline string. Four columns, looks like a help, but arg() parses your lines and finds out the arguments automatically.

  • Separate columns by two or more spaces - just like you would anyway.

  • Once parsed, each item will be represented by an array of fields, named char, word, type and help, respectively. If there's no short (char) or long (word) version for a parameter, just use a dash. Not for both, obviously.

  • Types are what they seem: bool means there's no value after the parameter; it's false if missing, true if present. The int and str types mean there must be a value, and int makes sure it's an integer. Optional parameters are not supported. Values can be separated by space or equal sign (i.e. "-a=4" or "-a 4")

  • After this first call, you have all your arguments neatly organized in a structure (dump it, you'll see) and you can query their values by name or number.

  • Function arg() has a second parameter for defaults so you'll never have to worry about missing values.

  • With the argument "??", as you see in the example, you get back a string that your command line tool can use as a help with arguments. Gone are the days when you had to keep those two in sync.

The arg() function itself


    function arg($x="",$default=null) {

        static $argtext = "";
        static $arginfo = [];

        /* helper */ $contains = function($h,$n) {return (false!==strpos($h,$n));};
        /* helper */ $valuesOf = function($s) {return explode(",",$s);};

        //  called with a multiline string --> parse arguments
        if($contains($x,"\n")) {

            //  parse multiline text input
            $argtext = $x;
            $args = $GLOBALS["argv"] ?: [];
            $rows = preg_split('/\s*\n\s*/',trim($x));
            $data = $valuesOf("char,word,type,help");
            foreach($rows as $row) {
                list($char,$word,$type,$help) = preg_split('/\s\s+/',$row);
                $char = trim($char,"-");
                $word = trim($word,"-");
                $key  = $word ?: $char ?: ""; if($key==="") continue;
                $arginfo[$key] = compact($data);
                $arginfo[$key]["value"] = null;
            }

            $nr = 0;
            while($args) {

                $x = array_shift($args); if($x[0]<>"-") {$arginfo[$nr++]["value"]=$x;continue;}
                $x = ltrim($x,"-");
                $v = null; if($contains($x,"=")) list($x,$v) = explode("=",$x,2);
                $k = "";foreach($arginfo as $k=>$arg) if(($arg["char"]==$x)||($arg["word"]==$x)) break;
                $t = $arginfo[$k]["type"];
                switch($t) {
                    case "bool" : $v = true; break;
                    case "str"  : if(is_null($v)) $v = array_shift($args); break;
                    case "int"  : if(is_null($v)) $v = array_shift($args); $v = intval($v); break;
                }
                $arginfo[$k]["value"] = $v;

            }

            return $arginfo;

        }

        if($x==="??") {
            $help = preg_replace('/\s(bool|int|str)\s+/'," ",$argtext);
            return $help;
        }

        //  called with a question --> read argument value
        if($x==="") return $arginfo;
        if(isset($arginfo[$x]["value"])) return $arginfo[$x]["value"];
        return $default;

    }

I hope this helps a lot of lost souls out there, like I was. May this little function shed a light upon the beauty of not having to write a help AND a parser and keeping them in sync... Also, once parsed, this approach is lightning fast since it caches the variables so you can call it as many times as you want. It acts like a superglobal.

Also available on my GitHub Gist.

2 of 2
7

You can retrieve the "raw" arguments using $argv. See also: http://www.php.net/manual/de/reserved.variables.argv.php

Example: php file.php a b c

$argv will contain "file.php", "a", "b" and "c".

Use getopts to get the parameters "parsed", PHP will do the dirty job for you. So it's probably the best way to go in your case as you want to pass the parameters with --options. Have a close look at http://www.php.net/manual/de/function.getopt.php It describes the function well.

🌐
Quora
quora.com › How-can-you-get-an-array-of-arguments-from-the-command-line-in-PHP-CLI
How to get an array of arguments from the command-line in PHP (CLI) - Quora
Answer: Two ways to do this: 1. If you are writing a PHP script to be used from the command line, just use $argc and $argv[]. Note: $argv[0] is the script name itself, so we start at $argv[1]. 2. If you are testing a server-side web script from ...
🌐
YouTube
youtube.com › buildamodule
122. How to pass arguments to a custom PHP script for use with the Drush php-script command - YouTube
This is one of over videos in a -hour series on http://buildamodule.com called "Change Management and Version Control". This collection is currently being r...
Published   October 5, 2022
Views   268