Table of Contents
Detailed explanation of php command line (CLI) parameters
Run php in interactive shell mode
Running the built-in Web server
Find the PHP configuration file
View class/function/extension information
Syntax check
Command line script development

PHP command line

May 17, 2018 am 09:09 AM
php Command Line


  • Detailed explanation of php command line (CLI) parameters

    • Run php in interactive shell mode

    • Run the built-in web server

    • Find the PHP configuration file

    • View classes/functions/ Extended information

    • Syntax check

  • Command line script development

PHP as a As a web development language, we usually run PHP in the Web Server and access it using a browser, so we rarely pay attention to its command line operations and the use of related parameters. However, especially on Unix-like operating systems, PHP can As a scripting language, it performs processing tasks similar to those of a shell.

Detailed explanation of php command line (CLI) parameters

To view all command line parameters of PHP, use the php -h command. We will explain most of the commonly used command line parameters one by one to deepen our understanding of PHP's capabilities, use PHP on the server command line more quickly or debug various problems that arise due to unfamiliarity with the environment.

-a               以交互式shell模式运行
-c | 指定php.ini文件所在的目录
-n               指定不使用php.ini文件
-d foo[=bar]     定义一个INI实体,key为foo,value为'bar'
-e               为调试和分析生成扩展信息
-f         解释和执行文件.
-h               打印帮助
-i               显示PHP的基本信息
-l               进行语法检查 (lint)
-m               显示编译到内核的模块
-r         运行PHP代码,不需要使用标签 ..?>
-B   在处理输入之前先执行PHP代码
-R         对输入的没一行作为PHP代码运行
-F         Parse and execute  for every input line
-E     Run PHP  after processing all input lines
-H               Hide any passed arguments from external tools.
-S : 运行内建的web服务器.
-t      指定用于内建web服务器的文档根目录
-s               输出HTML语法高亮的源码
-v               输出PHP的版本号
-w               输出去掉注释和空格的源码
-z         载入Zend扩展文件 .
 
args...          传递给要运行的脚本的参数. 当第一个参数以-开始或者是脚本是从标准输入读取的时候,使用--参数
 
--ini            显示PHP的配置文件名
 
--rf       显示关于函数  的信息.
--rc       显示关于类  的信息.
--re       显示关于扩展  的信息.
--rz       显示关于Zend扩展  的信息.
--ri       显示扩展  的配置信息.
Copy after login

The above lists all the parameters of the PHP command and their comments. Next, we will give examples of the more commonly used parameters.

Run php in interactive shell mode

Friends who have used Python are familiar with Python’s interactive shell. Under the command line, if we directly enter the python command, we will enter python. Interactive shell program, you can then perform some computing tasks interactively.

In the PHP command line, similar functions are also provided. Use the -a parameter to enter interactive shell mode.

In this shell, we can perform some simple tasks without always creating a new php file.

For more detailed instructions, please refer to the official documentation

Running the built-in Web server

Starting from PHP 5.4.0, PHP’s command line mode provides a built-in Built web server. Use -S to start running the web service.

Assume that we are currently in the directory /Users/mylxsw/codes/php/aicode/demo. In this directory, there is an index.php file.

$ ls
index.php
$ cat index.php
<?php echo "Hello, PHPER!";
Copy after login

In this directory, execute the following command to start the built-in web server, and use the current directory as the working directory by default

$ php -S localhost:8000
PHP 5.6.3 Development Server started at Wed Jun 10 15:49:41 2015
Listening on http://localhost:8000
Document root is /Users/mylxsw/codes/php/aicode/demo
Press Ctrl-C to quit.
Copy after login

We open another shell window, Request http://localhost:8000/ to see the script output

$ curl -is http://localhost:8000/
HTTP/1.1 200 OK
Host: localhost:8000
Connection: close
X-Powered-By: PHP/5.6.3
Content-type: text/html;
 
Hello, PHPER!
Copy after login

In the window where the web service is running, you can see the output log information

Above we are starting When building the server, only the -S parameter was specified to let PHP run as a web server. At this time, PHP will use the current directory as the working directory, so return to the current directory to find the requested file. We can also use the -t parameter. Specify another directory as the working directory (document root).

For more details, please refer to the official documentation.

Find the PHP configuration file

Sometimes, due to the confusion of software installation on the server, we may have installed multiple versions of the PHP environment. At this time, how to locate our PHP program? Which configuration file is used is more important. In the PHP command line parameters, the –ini parameter is provided. Using this parameter, you can list the current PHP configuration file information.

$ php --ini
Configuration File (php.ini) Path: /usr/local/etc/php/5.6
Loaded Configuration File:         /usr/local/etc/php/5.6/php.ini
Scan for additional .ini files in: /usr/local/etc/php/5.6/conf.d
Additional .ini files parsed:      (none)
 
$ /usr/local/php/bin/php --ini
Configuration File (php.ini) Path: /usr/local/php/etc/
Loaded Configuration File:         /usr/local/php/etc/php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)
Copy after login

We have installed two versions of PHP on the above server. As you can see from the above, using the php –ini command can easily locate which configuration file the current PHP command will use.

View class/function/extension information

Usually, we can use the php –info command or use the function phpinfo() in the php program on the web server to display php information, and then Finding information about related classes, extensions or functions is really troublesome.

$ php --info | grep redis
redis
Registered save handlers => files user redis
This program is free software; you can redistribute it and/or modify
Copy after login

We can use the following parameters to view this information more conveniently

--rf       显示关于函数  的信息.
--rc       显示关于类  的信息.
--re       显示关于扩展  的信息.
--rz       显示关于Zend扩展  的信息.
--ri       显示扩展  的配置信息.
Copy after login

For example, we want to view the configuration information of extended redis

$ php --ri redis
 
redis
 
Redis Support => enabled
Redis Version => 2.2.7
Copy after login

View redis class information

$ php --rc redis
Class [  class Redis ] {
 
  - Constants [19] {
    Constant [ integer REDIS_NOT_FOUND ] { 0 }
    ...
  - Methods [201] {
    ...
    Method [  public method echo ] {
    }
    ...
Copy after login

View function printf information

$ php --rf printf
Function [  function printf ] {
 
  - Parameters [2] {
    Parameter #0 [  $format ]
    Parameter #1 [  ...$args ]
  }
}
Copy after login

Syntax check

Sometimes, we only need to check whether the php script exists Syntax errors without executing it, such as checking PHP files for syntax errors in some editors or IDEs.

Use -l (--syntax-check) to perform syntax check only on PHP files.

$ php -l index.php
No syntax errors detected in index.php
Copy after login

If there is a syntax error in our index.php at this time

$ php -l index.php
PHP Parse error:  syntax error, unexpected &#39;echo&#39; (T_ECHO) in index.php on line 3
 
Parse error: syntax error, unexpected &#39;echo&#39; (T_ECHO) in index.php on line 3
Errors parsing index.php
Copy after login

Command line script development

When using PHP to develop command line scripts At the same time, it is obviously different from developing web programs. In web programs, we can provide different inputs for the PHP environment by changing the parameters of the URL. But how to obtain external input in the command line script program?

在使用C语言开发程序时,我们通常会在main函数中提供两个可选的参数int main(int argc, char *argv[]),这两个参数就是从命令行提供的输入参数。在PHP中,提供了两个全局变量$argc和$argv用于获取命令行输入。

  • $argc 包含了 $argv数组包含元素的数目

  • $argv 是一个数组,包含了提供的参数,第一个参数总是脚本文件名称

假设我们有一个名为console.php的命令行脚本文件

<?php echo &#39;命令行参数个数: &#39; . $argc . "n";
echo "命令行参数:n";
foreach ($argv as $index => $arg) {
    echo "    {$index} : {$arg}n";
}
Copy after login

在命令行下执行该脚本

$ php console.php hello world
命令行参数个数: 3
命令行参数:
    0 : console.php
    1 : hello
    2 : world
Copy after login

可以看到,第0个参数是我们执行的脚本名称。需要注意的是,如果提供的第一个参数是以-开头的话,需要在前面增加–,以告诉php这后面的参数是提供给我们的脚本的,而不是php执行文件的(php -r ‘var_dump($argv);’ — -h)。

另外,在脚本中,我们可以通过php_sapi_name()函数判断是否是在命令行下运行的

$ php -r &#39;echo php_sapi_name(), PHP_EOL;&#39;
cli
Copy after login

参考文献

  • Using PHP from the command line

The above is the detailed content of PHP command line. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles