search
HomeBackend DevelopmentPHP TutorialA brief discussion on how to obtain command line parameters in PHP

In the PHP CLI command line, it is necessary to provide parameters for the command line script like GET and POST on the web page; so how to obtain these command line parameters? The following article will show you how to obtain command line parameters in PHP, and introduce the $argv variable and getopt() function.

A brief discussion on how to obtain command line parameters in PHP

$argv Gets a list of all space-separated parameters

This variable is probably an access parameter variable that everyone uses more often. . It is a fixed variable prepared by PHP for us to obtain the parameter array passed to the script.

print_r($argv);
// php 如何获取PHP命令行参数.php --a=1 -b=2 -c=3 -d=4 --e=5 ccc ddd 
// Array
// (
//     [0] => 如何获取PHP命令行参数.php
//     [1] => --a=1
//     [2] => -b=2
//     [3] => -c=3
//     [4] => -d=4
//     [5] => --e=5
//     [6] => ccc
//     [7] => ddd
// )

This array is separated by spaces between parameters. The first element is the name of the currently running script file. That is to say, regardless of whether there are parameters or not, this variable must have an $argv[0] representing the current script file name.

In daily development needs, it is actually enough to use this variable. But this is obviously not our topic today. Everyone noticed that in the above code we have many parameters in the form of -x=xxx. Are parameters in this form very similar to Linux command options? Yes, this is What we’re going to focus on today: getting options from a command line argument list.

getopt() Gets options from the command line parameter list

In fact, it is such a simple function, we can get the specified command just like Linux command options value. And instead of being separated by spaces like $argv, the command option function will encapsulate these command options into an array, forming an array with the option name as the key and the content after the equal sign as the value, which is more convenient for us to use.

// php 如何获取PHP命令行参数.php --a=1 -b=2 -c=3 -d=4 --e=5 ccc ddd 
print_r(getopt('a:b:c:d:e:f:'));
// Array
// (
//     [b] => 2
//     [c] => 3
//     [d] => 4
// )

Isn’t it amazing and very intuitive? We directly got the contents of b, c, and d in the form of key-value arrays with a very clear format. Some students want to ask, where are a and e? What about ccc and ddd at the back?

The first thing to note is that ccc and ddd are not standard option parameters. That is to say, the content received by this function is the option starting with -, so ccc and ddd will not be output here, and you need to pay attention to it. Unfortunately, non-option parameters will interrupt the acquisition of option parameters. If you continue to add options starting with - after ccc, you will not be able to obtain them. We will see this later. And what about the option parameters starting with --? Let’s look directly at the long option function below.

Long option

// php 如何获取PHP命令行参数.php --a=1 -b=2 -c=3 -d=4 --e=5 ccc ddd 
print_r(getopt('', ['a:','b:','c:','d:','e:','f:']));
// Array
// (
//     [a] => 1
//     [e] => 5
// )

Yes, the second parameter of the getopt() function is to define this kind of long option at the beginning, and it should be noted that , the first parameter is of string type, and the second long option parameter is of array type. Then if we combine them, of course we can get all the parameter information!

// php 如何获取PHP命令行参数.php --a=1 -b=2 -c=3 -d=4 --e=5 ccc ddd 
print_r(getopt('a:b:c:d:e:f:', ['a:','b:','c:','d:','e:','f:']));
// Array
// (
//     [a] => 1
//     [b] => 2
//     [c] => 3
//     [d] => 4
//     [e] => 5
// )

OK, there is no problem in getting the parameter options. Careful students must have discovered another problem. Why is there a colon after the option name defined in the parameter of the getopt() function? This involves our colon rules, please read directly below.

Colon rules

The first two parameters of getopt() support a set of rules for option acquisition:

  • Individual characters (No values ​​accepted)
  • Characters followed by a colon (value required for this option)
  • Characters followed by two colons (value for this option optional)

Let’s take a look directly through the code.

// 一
// php 如何获取PHP命令行参数.php --a=1 -b=2 -c=3 -d=4 --e=5 ccc ddd 
print_r(getopt('abcdef'));
// Array
// (
//     [b] => 
//     [c] => 
//     [d] => 
// )

// 二
// php 如何获取PHP命令行参数.php -f
print_r(getopt('f::'));
// Array
// (
//     [f] => 
// )
print_r(getopt('f:'));
// Array
// (
// )

// 三
// php 如何获取PHP命令行参数.php -f 22
print_r(getopt('f::'));
// Array
// (
//     [f] => 
// )
print_r(getopt('f:'));
// Array
// (
//     [f] => 22
// )

// 四
// php 如何获取PHP命令行参数.php -f=22
print_r(getopt('f::'));
// Array
// (
//     [f] => 22
// )
print_r(getopt('f:'));
// Array
// (
//     [f] => 22
// )

This paragraph is relatively long, let’s look at it piece by piece. The first is abcdef without colon. The returned array contains keys but no values. Corresponding to the above rules, the values ​​of these parameter options are not accepted. When you pass these parameter options, they only have key names and empty content.

The second paragraph defines a parameter but does not give a value. At this time, the double colon :: will have a key name, while the single colon : will have nothing.

The third paragraph is the option value in the form of spaces. Double colon:: There is a key name but no value. Single colon: The key value is normal.

The fourth paragraph is the option value in the form of equal sign =. Both single and double colons receive the key value normally.

Option parameter interruption

We mentioned the problem of parameter interruption above, that is, if a non-option parameter parameter appears after the option parameter, getopt() All content following this non-option parameter can no longer be obtained.

// php 如何获取PHP命令行参数.php -f=22 aa -b=33
// 选项的解析会终止于找到的第一个非选项,之后的任何东西都会被丢弃。
// Array
// (
//     [f] => 22
// )

Through this test, it can be clearly seen that the following b option cannot be obtained. At this time, if we want to know where the option parameter is or which parameter is interrupted, we can use the third parameter of the getopt() function.

// php 如何获取PHP命令行参数.php -f=22 aa -b=33
$optind = null;
getopt('f:b:', [], $optind);
echo $optind, PHP_EOL; // 返回中断位置的索引值,2
echo $argv[$optind], PHP_EOL; // 等同于 $argv 的索引顺序,aa

The comment has been written very clearly. The third parameter will call back the index of the parameter option interruption position, and this index is consistent with the index sequence position of $argv.

Summary

To be honest, before reading the document, I really only knew that there is an $argv variable that can be used to obtain the parameters of the command line script. Through this study Only then did I discover that there is such a powerful option parameter function. The learning process is very simple. How to apply it to real projects is the key. Come on, study hard and practice hard!

测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202006/source/%E5%A6%82%E4%BD%95%E8%8E%B7%E5%8F%96PHP%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%8F%82%E6%95%B0.php

推荐学习:《PHP视频教程

The above is the detailed content of A brief discussion on how to obtain command line parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool