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</code></code></file></file></file></path></file></file></code></file>
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"
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" }</file>
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); ?>
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" }
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
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 executionPHP calls Linux command line execution file compression command_PHP tutorial
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!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Chinese version
Chinese version, very easy to use

WebStorm Mac version
Useful JavaScript development tools

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.