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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1255
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

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 and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

See all articles