本文将介绍 PHP 中的 shell_exec()
和 exec()
函数。我们知道,要在系统中执行命令,我们需要使用相应操作系统的 shell,但如果我们需要在 PHP 等编程语言的帮助下执行相同的命令,我们就需要使用这两个函数。可以使用这两个函数中的任何一个,但它们在成功执行后的输出结果是不同的。
shell_exec() 函数
shell_exec()
函数是 PHP 中的一个内置函数,用于通过 shell 执行命令并以字符串形式返回完整输出。对于习惯使用 *nix
的人来说,shell_exec
是回车操作符的别名。如果命令执行失败,它将返回 NULL
,而且错误检查的值也不可靠。当 PHP 在安全模式下运行时,该函数将被禁用。
语法
string shell_exec( $cmd )
参数:shell_exec() 函数只传递一个参数($cmd),因为它包含要执行的命令。
返回值: 返回已执行的命令,如果出现错误,则返回 NULL。
示例 1:
<?php
// Command
$command = "DATE";
// Passing the command to the function
$cmd_output = shell_exec($command);
echo $cmd_output;
?>
输出结果:
The current date is 18-03-2024. Enter the new date: (dd-mm-yy)
示例 2:
<?php
// Command
$command = "TIME";
// Passing the command to the function
$cmd_output = shell_exec($command);
echo $cmd_output;
?>
运行结果:
The current time is: 23:05:06.81. Enter the new time:
exec()函数
exec() 函数是 PHP 中的一个内置函数,用于执行外部程序并返回最后一行输出。如果命令没有正常运行,它也会返回 NULL。它的输出结果与 shell_exec() 函数不同。它执行命令,并以数组的形式给出该命令的所有输出,同时还给出一些额外的信息,我们可以用这些信息来检查命令是否成功执行。
string exec( $command, $output, $return_var )
此函数接受三个参数:
$command
:用于保存要执行的命令。$output
:用于指定数组,该数组将填充命令的每一行输出。$return_var
: 该参数与输出参数一起出现,将返回已执行命令的状态,并写入该变量。
返回值: 返回已执行的命令。
示例一:
<?php
// Command to be executed in the shell
$command = "DATE";
// Calling exec function
exec($command, $output_array, $cmd_status);
echo "Command status - ".$cmd_status." <br><br>";
echo var_dump($output_array)
?>
运行结果:
Command status - 1
array(2) { [0]=> string(31) "The current date is: 02-06-2023"
[1]=> string(30) "Enter the new date: (dd-mm-yy)" }
示例 2 :
<?php
// Command to be executed in the shell
$command = "TIME";
// Calling exec function
exec($command, $output_array, $cmd_status);
echo "Command status - ".$cmd_status." <br><br>";
echo var_dump($output_array)
?>
运行结果:
Command status - 1
array(2) { [0]=> string(32) "The current time is: 23:31:03.81"
[1]=> string(19) "Enter the new time:" }
shell_exec() 与 exec() 函数的区别:
编号 | shell_exec() | exec() |
---|---|---|
1 | shell_exec() 函数是 PHP 中的一个内置函数,用于通过 shell 执行命令,并以字符串形式返回完整的输出。 |
exec() 函数是 PHP 的一个内置函数,用于执行外部程序并返回最后一行输出。如果没有命令正常运行,它也会返回 NULL。 |
2 | shell_exec() 函数以字符串形式提供完整的输出。 |
exec() 函数可以以第二个参数指定的数组形式提供所有输出。 |
3 | 当出现错误或程序没有输出时,shell_exec() 函数都可以返回空值。 |
exec() 函数只能在没有命令正常执行的情况下返回空值。 |
shell_exec() 和 exec() 函数的区别
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动成果。
转载请注明:文章转载自 有区别网 [http://www.vsdiffer.com]
本文标题:shell_exec() 和 exec() 函数的区别
本文链接:https://www.vsdiffer.com/vs/difference-between-shell_exec-and-exec-functions.html
免责声明:以上内容仅代表 个人看法、理解、学习笔记、总结和研究收藏。不保证其正确性,因使用而带来的风险与本站无关!如本网站内容冒犯了您的权益,请联系站长,邮箱: ,我们核实并会尽快处理。