📜  解释 shell_exec() 和 exec() 函数之间的区别

📅  最后修改于: 2022-05-13 01:56:26.224000             🧑  作者: Mango

解释 shell_exec() 和 exec() 函数之间的区别

在本文中,我们将了解PHP中的 shell_exec() 和 exec() 函数。众所周知,为了在系统中执行命令,我们需要各自操作系统的 shell,但是如果我们需要借助PHP之类的编程语言来执行相同的命令,那么我们使用这两个函数。我们使用这两个函数中的任何一个,但它们在输出方面有所不同,它们将在成功执行后给出。请参考PHP | shell_exec() 与 exec()函数。

shell_exec()函数: shell_exec()函数是PHP中的一个内置函数,用于通过 shell 执行命令并将完整的输出作为字符串返回。 shell_exec 是反引号运算符的别名,适用于那些习惯于 *nix 的人。如果命令失败,它将返回 NULL,并且这些值对于错误检查不可靠。当PHP在安全模式下运行时,此函数将被禁用。

句法:

string shell_exec( $cmd )

参数: shell_exec()函数只传递一个参数($cmd),因为它包含要执行的命令。

返回值:如果发生错误则返回执行的命令或NULL。

示例 1:

PHP


PHP


PHP

"; echo var_dump($output_array)    ?>


PHP

"; echo var_dump($output_array)    ?>


输出

The current date is 08-07-2021. Enter the new date: (dd-mm-yy)

示例 2:

PHP


输出:

The current time is: 21:05:01.82. Enter the new time: 

exec()函数: exec()函数是PHP中的一个内置函数,用于执行外部程序并返回输出的最后一行。如果没有命令正常运行,它也会返回 NULL。它在提供 wrt shell_exec() 函数的输出方面有所不同。它执行命令并以数组的形式给出该命令的所有输出,它还提供了一些额外的信息,我们可以使用这些信息来检查命令是否成功执行。

句法:

string exec( $command, $output, $return_var )

参数:此函数将接受三个参数:

  • $command:用来存放要执行的命令。
  • $output:用于指定将用命令的每一行输出填充的数组。
  • $return_var:此参数与输出参数一起存在,然后它返回将写入此变量的已执行命令的状态。

返回值:返回执行的命令。

示例 1:

PHP


"; echo var_dump($output_array)    ?>

输出:

Command status - 1

array(2) { [0]=> string(31) "The current date is: 08-07-2021" 
           [1]=> string(30) "Enter the new date: (dd-mm-yy)" } 

示例 2:

PHP


"; echo var_dump($output_array)    ?>

输出:

Command status - 1

array(2) { [0]=> string(32) "The current time is: 21:38:09.81" 
           [1]=> string(19) "Enter the new time:" }

shell_exec() 和 exec()函数的区别:

 

shell_exec()

exec()

1.

The shell_exec() function is an inbuilt function in PHP that is used to execute the commands via shell and return the complete output as a string.

The exec() function is an inbuilt function in PHP that is used to execute an external program and returns the last line of the output. It also returns NULL if no command runs properly.

2.

The shell_exec() function provides complete output as a string.

The exec() function can provide all output in the form of an array specified as the second parameter.

3.

The shell_exec() function can return null for both cases when an error occurs or the program produces no output.

The exec() function can return null only in the case when no command executes properly.