search
HomeBackend DevelopmentPHP ProblemHow to get PHP command line parameters

This article will introduce to you how to obtain PHP command line parameters. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How to get PHP command line parameters

How to get PHP command line parameters

Students who use PHP development will have more or less contact with the CLI command line. There are often some scheduled tasks or some scripts that are more convenient to process directly using the command line. Sometimes we need to provide parameters for these command line scripts like GET and POST on web pages. For example, in a script that makes statistics on certain dates, you need to pass a date to it, so that we can count some data on the specified date. This type of requirement should be very common, so how do we receive these command line parameters? Today, let’s introduce this aspect.

$argv Gets all space-separated parameter lists

This variable is probably a 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 value just like Linux command options. 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 starting with --, and it should be noted that the first parameter is String type, 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 (not accepted value)

  • The character followed by a colon (this option requires a value)

  • The character followed by two colons (the value of this option can Select)

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() will no longer be able to obtain this Everything after the non-option parameters.

// 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

注释已经写得很清晰了,第三个参数会回调一个参数选项中断位置的索引,并且这个索引是和 $argv 的索引顺序位置一致的。

总结

说实话,在没看文档前真的只知道有一个 $argv 变量可以用来获取命令行脚本的参数,通过这次学习才发现原来还有一个这么强大的选项参数函数。学习的过程非常简单,如何运用到真实的项目中才是关键所在,加油学习,努力实践吧!

测试代码:

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 How to get PHP command line parameters. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.