Home Backend Development PHP Tutorial PHP command line execution example

PHP command line execution example

Mar 14, 2018 am 11:21 AM
php Command Line implement

This article mainly shares with you the following command line mode option parameters provided by the PHP binary file (that is, the php.exe program). You can query these parameters at any time through the PHP -h command.

Usage: php [options] [-f] <file> [args...]
      php [options] -r <code> [args...]
      php [options] [-- args...]
 -s               Display colour syntax highlighted source.
 -w               Display source with stripped comments and whitespace.
 -f <file>        Parse <file>.
 -v               Version number
 -c <path>|<file> Look for php.ini file in this directory
 -a               Run interactively
 -d foo[=bar]     Define INI entry foo with value 'bar'
 -e               Generate extended information for debugger/profiler
 -z <file>        Load Zend extension <file>.
 -l               Syntax check only (lint)
 -m               Show compiled in modules
 -i               PHP information
 -r <code>        Run PHP <code> without using script tags <?..?>
 -h               This help
 args...          Arguments passed to script. Use -- args when first argument 
                  starts with - or script is read from stdin
Copy after login

The CLI SAPI module has the following three different methods to obtain the PHP code you want to run:

In the windows environment, try to use double quotes, and in the linux environment try to use single quotes Complete with quotation marks.

Let PHP run the specified file.

php my_script.php 
php -f  "my_script.php"
Copy after login

Both of the above methods (with or without the -f parameter) can run the given my_script.php file. You can choose any file to run. The PHP scripts you specify do not have to have a .php extension. They can have any file name and extension.

Run PHP code directly on the command line.

php -r "print_r(get_defined_constants());"

When using this method, please pay attention to the substitution of shell variables and the use of quotation marks.

Note: Please read the above example carefully, there are no start and end markers when running the code! With the -r parameter, these markers are unnecessary and will cause syntax errors.

Provide the PHP code that needs to be run through standard input (stdin).

The above usage provides us with very powerful functions, allowing us to dynamically generate PHP code and run these codes through the command line as shown in the following example:

$ some_application | some_filter | php | sort -u >final_output.txt

The above three methods of running code cannot be used at the same time.

Like all shell applications, the PHP binary (php.exe file) and the PHP script it runs can accept a series of parameters. PHP has no limit on the number of arguments passed to a script (the shell has a limit on the number of characters on the command line, but you usually won't exceed that limit). The arguments passed to your script are available in the global variable $argv . The zero-indexed member of this array is the name of the script (when the PHP code comes from standard input and is run directly from the command line with the -r parameter, the name is "-"). In addition, the global variable $argc stores the number of member variables in the $argv array (not the number of parameters passed to the script program).

As long as the parameters you send to your script do not start with the - symbol, you don't need to pay too much attention to anything. Passing parameters starting with - to your script will cause an error because PHP will think it should handle these parameters itself. You can use the parameter list separator -- to solve this problem. After PHP parses the parameters, all parameters after this symbol will be passed to your script as is.

# 以下命令将不会运行 PHP 代码,而只显示 PHP 命令行模式的使用说明:
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [args...]
[...]
 
# 以下命令将会把“-h”参数传送给脚本程序,PHP 不会显示命令行模式的使用说明:
$ php -r "var_dump($argv);" -- -h
array(2) {
  [0]=>
  string(1) "-"
  [1]=>
  string(2) "-h"
}
Copy after login

Besides this, we have another way to use PHP for shell scripts. You can write a script and start the first line with #!/usr/bin/php, followed by normal PHP code enclosed by PHP start and end tags, and then set up the correct execution for the file Attributes. This method enables the file to be executed directly like a shell script or PERL script.

#!/usr/bin/php
<?php
    var_dump($argv);
?>
Copy after login

Assuming that the file is renamed test and placed in the current directory, we can do the following:

$ chmod 755 test
$ ./test -h -- foo
array(4) {
  [0]=>
  string(6) "./test"
  [1]=>
  string(2) "-h"
  [2]=>
  string(2) "--"
  [3]=>
  string(3) "foo"
}
Copy after login

As you can see, when you send the script to the script starting with - parameters, the script can still run normally.

-------------------------------------------------- ----------------------------------Command options-------------- ---------------------------------------

Form 23-3. Command line options

Option name

Description

-s

Display source files with syntax highlighting.

This parameter uses the built-in mechanism to parse the file and generate an HTML highlighted version of it and write the result to standard output. Please note that all this process does is generate an HTML tag block of [...] and does not contain any HTML headers.

Note: This option cannot be used with the -r parameter at the same time.

-w

Display the source code with comments and spaces removed.

Note: This option cannot be used together with the -r parameter.

-f

Parse and run the given file name. This parameter is optional and does not need to be added. It only needs to specify the file name that needs to be run.

-v

Write the version information of PHP, PHP SAPI and Zend to the standard output. For example:

$ php -v PHP 4.3.0-dev (cli), Copyright (c) 1997-2002 The PHP Group Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies

-c

Using this parameter, you can specify a directory where the php.ini file is placed, or directly specify a custom INI file, whose file name may not be php.ini. For example:

$ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.php

-a

Run PHP interactively.

-d

Use this parameter to set the value of the variable in the php.ini file. The syntax is:

-d configuration_directive[ =value]

Example:

# Ommiting the value part will set the given configuration directive to "1" $ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(1) "1" # Passing an empty value part will set the configuration directive to "" php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo );' string(0) "" # The configuration directive will be set to anything passed after the '=' character $ php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo) ;' string(2) "20" $ php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(15) "doesntmakesense"

- e

Generate extended information for debuggers, etc.

-z

Load the Zend extension library. If only a file name is given, PHP will try to load the extension library from the default path of your system's extension library (on Linux systems, this path is usually specified by /etc/ld.so.conf). If you specify a filename with an absolute path, the system's default path to the extension library will not be used. If you specify a filename with a relative path, PHP will only try to load the extension relative to the current directory.

-l

This parameter provides a convenient method for syntax checking of the specified PHP code. If successful, the string No syntax errors detected in is written to standard output, and the shell returns a value of 0. If it fails, Errors parsing will be written to standard output along with internal parser error messages, and the shell return value will be set to 255.

This parameter will not be able to check for fatal errors (such as undefined functions). If you want to detect fatal errors, please use the -f parameter.

Note: This parameter cannot be used with -r.

-m

Using this parameter, PHP will print out the built-in and loaded PHP and Zend modules:

$ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [Zend Modules]

-i This command line parameter will call the phpinfo() function and print out the result. If PHP is not working properly, we recommend that you execute the php -i command to see if there are any error messages output before or in the corresponding place in the information table. Please note that the output content is in HTML format, so the output information is larger.

-r

Use this parameter to run PHP code on the command line. You do not need to add the PHP starting and ending identifiers (), otherwise it will cause syntax parsing errors.

Note: When using this form of PHP, special care should be taken to avoid conflicts with command line parameter substitutions performed by the shell environment.

Example of displaying syntax parsing errors

$ php -r "$foo = get_defined_constants();" Command line code(1) : Parse error - parse error, unexpected '='

The problem here is that even if double quotes " are used, sh/bash still implements parameter substitution. Since $foo is not defined, its position becomes a null character after being replaced, so at runtime, it is actually read by PHP The code taken is:

$ php -r " = get_defined_constants();"

The correct method is to use single quotes '. In a string quoted with single quotes, variables will not Restored to its original value by sh/bash php -r '$foo = get_defined_constants(); var_dump($foo);' array(370) { ["E_ERROR"]=> int( 1) ["E_WARNING"]=> int(2) ["E_PARSE"]=> int(4) ["E_NOTICE"]=> int(8) ["E_CORE_ERROR"]=> [... ]

If you are using a shell other than sh/bash, you may encounter other problems. Please report any bugs you encounter, or send an email to phpdoc@lists.php.net. ##You may also encounter various problems when you try to introduce the shell's environment variables into the horse or use backslashes to escape characters. Please pay attention when using them!

Note: - r Valid in CLI SAPI, invalid in CGI SAPI.

-h Using this parameter, you can get a complete list of command line parameters and a brief description of the functions of these parameters.

PHP's command line mode allows PHP scripts to run completely independent of the WEB server. If you use a Unix system, you need to add a special line of code at the beginning of your PHP script so that it can be run independently. Execute so that the system knows what program to use to run the script. On Windows platforms, you can associate the double-click attributes of php.exe and .php files, or you can write a batch file to execute the script with PHP. . The first line of code added for Unix systems will not affect the running of the script under Windows, so you can also use this method to write cross-platform scripts. The following is an example of a simple PHP command line program.

Example 23-1. Trying to run a PHP script (script.php) from the command line

#!/usr/bin/phpThis is a command line PHP script with one option. Usage:

In the above script, we use the first line of special code to indicate that the file should be generated by PHP to execute. We are using the CLI version here, so no HTTP headers will be output. When you write command line applications in PHP, you can use two parameters: $argc and $argv. The value of the previous one is an integer one greater than the number of parameters (the name of the script being run is also considered a parameter). The second one contains an array of parameters, the first element of which is the name of the script, and the subscript is the number 0 ($argv[0]).

In the above program we checked whether the number of parameters is greater than 1 or less than 1. Even if the parameter is --help, -help, -h or -?, we still print out the help information and dynamically output the name of the script at the same time. If other parameters are received, we also display them.

If you want to run the above script under Unix, you need to make it an executable script, and then simply run script.php echothis or script.php -h. Under Windows, you can write a batch file for this:

@c:\php\cli\php.exe script.php %1 %2 %3 %4

Related recommendations :

Detailed explanation of PHP command line execution

PHP calls Linux command line execution file compression command_PHP tutorial

Command line execution on PHP

The above is the detailed content of PHP command line execution example. 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,

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

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

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