Table of Contents
Detailed explanation of how exec, system and other functions in PHP call system commands" >Detailed explanation of how exec, system and other functions in PHP call system commands
PHP执行系统外部命令:exec()、passthru()、system()、shell_exec()
Home Backend Development PHP Tutorial The usage scenarios of the four PHP functions shell_exec, exec, passthru, and system

The usage scenarios of the four PHP functions shell_exec, exec, passthru, and system

May 03, 2018 am 09:36 AM
exec php shell

This article mainly introduces the usage scenarios of the four PHP functions shell_exec, exec, passthru, and system. It has certain reference value. Now I share it with everyone. Friends in need can refer to it


#You can execute related commands of the operating system. I feel that one application scenario is to start another process in the background to execute some time-consuming content without displaying the results in the front desk. It is a bit Similar to scheduled tasks, it can also replace queues in simple scenarios. For example, there is a file abc.php, which contains information related to sending emails, which is relatively time-consuming. In other files, after processing the normal logic, I want to send an email, but I don’t want to care whether the email is successful or not. As long as it is executed, that’s it:

1

2

3

4

5

6

7

8

//正常逻辑

...

//处理费时的

exec('php abc.php  > /dev/null &');

// 或者

exec('php abc.php | at now');

//继续走你

...

Copy after login

Similar to this, the above is only for Linux, There may be permission issues or path issues, and Windows may need other functions to handle it.

Detailed explanation of how exec, system and other functions in PHP call system commands

PHP’s built-in functions exec and system can all call system commands (shell command), of course, there are also passthru, escapeshellcmd and other functions.


In many cases, using PHP’s exec, system and other functions to call system commands can help us complete our work better and faster. For example, exec helped me a lot when I was batch processing .rar files two days ago.

Today I will sort out the commonly used calling system functions and share my experience with everyone.

Note: If you want to use these two functions, the safe mode in php.ini must be turned off, otherwise PHP will not be allowed to call system commands for security reasons.

First, let’s take a look at the explanation of these two functions in the PHP manual:

exec --- Execute external programs

Syntax: string exec ( string command [, array &output [ , int &return_var]] )

 exec function analysis

 exec syntax: string exec(string command , string [array], int [return_var]);

 exec return value: String

 Exec parameter description

 Command – the command to be executed

 Array – is the output value

 return_var – is the return value 0 or 1. If 0 is returned, the execution is successful, and if 1 is returned, the execution fails.

 exec failed, debugging plan

  一个技巧就是使用管道命令, 使用 2>&1, 命令就会输出shell执行时的错误到$output变量, 输出该变量即可分析。

  如:

  exec('convert a.jpg b.jpg', $output, $return_val);

  改为:

  exec('convert a.jpg b.jpg 2>&1', $output, $return_val);

  print_r($output);

  说明 :

  exec( )执行给予的命令command,不过它并不会输出任何东西,它简单的从命令的结果中传回最后一行,如果你需要去执行一个命令,并且从命令去取得所有资料时,可以使用passthru( )这个函数。

  如果有给予参数array,则指定的数组将会被命令所输出的每一行填满,注意 : 如果数组先前已经包含了一些元素的话,exec( )将会把它附加在数组的后面,如果你不想要此函数附加元素的话,你可以在传递此数组给exec( )之前呼叫unset( )。

  如果有给予参数array和return_var,则传回执行的状态命令将会写到这个变量。

  注意 : 如果你允许来自使用者输入的资料,可以传递到此函数,那么你应该使用escapeshellcmd( )来确定此使用者无法哄骗(trick)系统来执行武断的(arbitrary)命令。

  注意 : 如果你使用此函数来启动一个程式,而且希望在背景里(background)执行的时候离开它,你必须确定此程式的输出是转向(redirected)到一个文件或是一些输出的资料流,否则PHP将会悬挂(hang)直到程式执行结束。

  system --- 执行外部程式并且显示输出

  语法 : string system ( string command [, int &return_var] )

  说明 :

  system( )执行给予的命令command,并且输出结果。如果有给予参数return_var,则执行命令的状态码将会写到这个变量。

  注意 : 如果你允许来自使用者输入的资料,可以传递到此函数,那么你应该使用escapeshellcmd( )来确定此使用者无法哄骗(trick)系统来执行武断的(arbitrary)命令。

  注意 : 如果你使用此函数来启动一个程式,而且希望在背景里(background)执行的时候离开它,你必须确定此程式的输出是转向(redirected)到一个文件或是一些输出的资料流,否则PHP将会悬挂(hang)直到程式执行结束。

  如果PHP是运作成伺服器模组,在输出每一行后,system( )会试着自动地清除web伺服器的输出缓冲。

  成功则传回命令的最后一行,失败则传回false。

  如果你需要去执行一个命令,并且从命令去取得所有资料时,可以使用passthru( )这个函数。

  这二个都是用来调用系统shell命令,

  不同点:

  exec可以把执行的结果全部返回到$output函数里(数组),$status是执行的状态 0为成功 1为失败

  systerm不需要提供$output函数,他是直接把结果返回出来,同样$return_var是执行的状态码 0为成功 1为失败

exec示例:

1

2

3

4

5

6

<?php 

      $a = exec("dir",$out,$status); 

      print_r($a); 

      print_r($out); 

      print_r($status); 

  ?>

Copy after login

1

2

3

4

5

6

7

8

<code class="hljs bash" style="padding:10px;background-color:rgb(63,63,63);color:rgb(220,220,220);font-size:13px;line-height:1.4;font-family:Menlo, Monaco, Consolas, &#39;Courier New&#39;, monospace;"><?php   

    <span class="hljs-variable" style="color:rgb(239,220,188);">$a</span> = <span class="hljs-built_in" style="color:rgb(204,147,147);">exec</span>(<span class="hljs-string" style="color:rgb(204,147,147);">"dir"</span>,<span class="hljs-variable" style="color:rgb(239,220,188);">$out</span>,<span class="hljs-variable" style="color:rgb(239,220,188);">$status</span>);   

    <span class="hljs-built_in" style="color:rgb(204,147,147);">print</span>_r(<span class="hljs-variable" style="color:rgb(239,220,188);">$a</span>);   

    <span class="hljs-built_in" style="color:rgb(204,147,147);">echo</span> <span class="hljs-string" style="color:rgb(204,147,147);">"<br>-----------------------------------------------------<br>"</span>; 

    <span class="hljs-built_in" style="color:rgb(204,147,147);">echo</span> <span class="hljs-string" style="color:rgb(204,147,147);">"<pre class="brush:php;toolbar:false">"</span>; 

    //<span class="hljs-built_in" style="color:rgb(204,147,147);">print</span>_r(<span class="hljs-variable" style="color:rgb(239,220,188);">$out</span>);  

    var_dump(<span class="hljs-variable" style="color:rgb(239,220,188);">$out</span>); 

    <span class="hljs-built_in" style="color:rgb(204,147,147);">echo</span> <span class="hljs-string" style="color:rgb(204,147,147);">"

"; echo "
-----------------------------------------------------
"
; print_r($status); ?>
Copy after login

system示例:

1

2

3

4

5

<?php 

    $a = system("dir",$out); 

    print_r($a); 

    print_r($out); 

?>

Copy after login

1

2

3

4

5

6

7

8

9

<code class="hljs xml" style="padding:10px;background-color:rgb(63,63,63);color:rgb(220,220,220);

font-size:13px;

line-height:1.4;

font-family:Menlo, Monaco, Consolas, &#39;Courier New&#39;, monospace;"><span class="php"><span class="hljs-meta" style="color:rgb(127,159,127);"><span class="php"><span class="hljs-meta"><?php</span></span></span><span class="php">  

    $a = system(</span><span class="hljs-string" style="color:rgb(204,147,147);"><span class="php"><span class="hljs-string" style="color:rgb(204,147,147);">"dir"</span></span></span><span class="php">,$out);  

    </span><span class="hljs-keyword" style="color:rgb(227,206,171);"><span class="php"><span class="hljs-keyword" style="color:rgb(227,206,171);">echo</span></span></span><span class="php"> </span><span class="hljs-string" style="color:rgb(204,147,147);"><span class="php"><span class="hljs-string" style="color:rgb(204,147,147);">"<pre class="brush:php;toolbar:false">"</span></span></span><span class="php">; 

    </span><span class="hljs-comment" style="color:rgb(127,159,127);"><span class="php"><span class="hljs-comment" style="color:rgb(127,159,127);">//print_r($a); </span></span></span><span class="php"> 

    var_dump($a); 

    </span><span class="hljs-keyword" style="color:rgb(227,206,171);"><span class="php"><span class="hljs-keyword" style="color:rgb(227,206,171);">echo</span></span></span><span class="php"> </span><span class="hljs-string" style="color:rgb(204,147,147);"><span class="php"><span class="hljs-string" style="color:rgb(204,147,147);">"

"; echo "
-----------------------------------------------------
"
; print_r($out); ?>
Copy after login

 大家可以运行一下看效果

PHP执行系统外部命令:exec()、passthru()、system()、shell_exec()

在php开发网站中,经常需要执行系统外部命令。php提供4种方法执行系统外部命令:exec()、passthru()、system()、 shell_exec()。下面一一介绍。在开始前,先检查下php配置文件php.ini中是有禁止这是个函数。找到 disable_functions,配置如下:

disable_functions =

如果“disable_functions=”后面有接上面四个函数,将其删除。默认php.ini配置文件中是不禁止你调用执行外部命令的函数的。

方法一:exec()

1

function exec(string $command,array[optional] $output,int[optional] $return_value)

Copy after login

php代码:

1

2

3

4

5

<?php

        echo exec("ls",$file);

        echo "</br>";

        print_r($file);

?>

Copy after login

执行结果:

1

2

test.php

Array( [0] => index.php [1] => test.php)

Copy after login

知识点:

exec 执行系统外部命令时不会输出结果,而是返回结果的最后一行,如果你想得到结果你可以使用第二个参数,让其输出到指定的数组,此数组一个记录代表输出的一 行,即如果输出结果有20行,则这个数组就有20条记录,所以如果你需要反复输出调用不同系统外部命令的结果,你最好在输出每一条系统外部命令结果时清空 这个数组,以防混乱。第三个参数用来取得命令执行的状态码,通常执行成功都是返回0。

方法二:passthru()

1

function passthru(string $command,int[optional] $return_value)

Copy after login

代码:

1

2

3

<?php

        passthru("ls");

?>

Copy after login

执行结果:

1

index.phptest.php

Copy after login

知识点:

passthru与system的区别,passthru直接将结果输出到浏览器,不需要使用 echo 或 return 来查看结果,不返回任何值,且其可以输出二进制,比如图像数据。

方法三:system()

1

function system(string $command,int[optional] $return_value)

Copy after login

代码:

1

2

3

<?php

        system("ls /");

?>

Copy after login

执行结果:

1

binbootcgroupdevetchomeliblost+foundmediamntoptprocrootsbinselinuxsrvsystmpusrvar

Copy after login

知识点:

system和exec的区别在于system在执行系统外部命令时,直接将结果输出到游览器,不需要使用 echo 或 return 来查看结果,如果执行命令成功则返回true,否则返回false。第二个参数与exec第三个参数含义一样。

方法四:反撇号`和shell_exec()

1

shell_exec() 函数实际上仅是反撇号 (`) 操作符的变体

Copy after login

代码:

1

2

3

<?php

        echo `pwd`;

?>

Copy after login

执行结果:

1

/var/www/html

Copy after login

相关推荐:

PHP正则匹配日期和时间(时间戳转换)的实例代码


The above is the detailed content of The usage scenarios of the four PHP functions shell_exec, exec, passthru, and system. 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
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Clair Obscur: Expedition 33 - How To Get Perfect Chroma Catalysts
2 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
1677
14
PHP Tutorial
1278
29
C# Tutorial
1257
24
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: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

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 and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

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.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

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

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles