如何正确实现PHP命令行读取参数
如果想实现PHP命令行读取参数,CLI可以从$_SERVER['argc']和$_SERVER['argv'']取得参数的个数和值。我们再建立一个文件,名字为testargs.php,脚本代码如下:
- #!C:phpphp.exe –q
- ?php
- //UNIX和Linux平台下应该为
#!/usr/local/bin/php –q - echo "测试获取参数:n";
- echo $_SERVER["argc"]."n";
- //显示传入的参数值,从索引1开始显示
- echo $_SERVER["argv"][1]."n";
- echo $_SERVER["argv"][2]."n";
- echo $_SERVER["argv"][3]."n";
- echo $_SERVER["argv"][4]."n";
- ?>
在命令行输入如下代码:
C:UsersJohn>testargs.php Always To Be Best
测试获取参数:
4
Always
To
Be
Best
因为我们输入了一串单词,为“Always To Be Best”,脚本参数以空格分隔。因此,PHP将其计为4个参数,下面对此说明。
$_SERVER["argc"]数组返回一个整型的数,代表从命令行上回车后一共输入了几个参数。
从PHP命令行读取参数范例中的结果已经看出,要访问已经传入的参数值,需要从索引1开始。因为脚本本身的文件已经占用了索引0,即$_SERVER["argv"][0]。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Dreamweaver Mac version
Visual web development tools

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
