php 与 shell 命令交互方法:exec() 函数:执行命令并获取输出。shell_exec() 函数:在独立 shell 进程中执行命令。popen() 函数:通过管道与命令双向通信。proc_open() 函数:提供了更高级的控制,可指定命令流。
PHP 如何与 Shell 命令互动?
在 PHP 程序中与 shell 命令交互可以扩展应用程序的可能性,从自动化任务到访问系统功能。本文将介绍使用 PHP 执行 shell 命令的不同方法,并提供实战案例。
exec() 函数
exec() 函数允许您执行 shell 命令并获取其输出。
$output = exec('ls -l');
echo $output;
shell_exec() 函数
shell_exec() 函数与 exec() 函数类似,但它会在一个单独的 shell 进程中执行命令。
立即学习“PHP免费学习笔记(深入)”;
$output = shell_exec('ls -l');
echo $output;
popen() 函数
popen() 函数打开一个管道,使您可以与 shell 命令以双向通信。
$handle = popen('ls -l', 'r');
while (($buffer = fgets($handle)) !== false) {
echo $buffer;
}
fclose($handle);
proc_open() 函数
proc_open() 函数提供了更高级别的控制,允许您指定命令的 STDIN、STDOUT 和 STDERR 流。
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("pipe", "w") // stderr is a file to write to
);
$process = proc_open('ls -l', $descriptorspec, $pipes);
实战案例:解析 Linux 文件权限
// 获取文件权限
$output = shell_exec('ls -l /var/www/html');
// 解析输出
$lines = explode("n", $output);
array_shift($lines); // 移除标题行
foreach ($lines as $line) {
$parts = explode(' ', $line);
$permissions = $parts[0];
// 提取权限信息
$owner = substr($permissions, 1, 3);
$group = substr($permissions, 4, 3);
$other = substr($permissions, 7, 3);
echo "Owner: $owner, Group: $group, Other: $othern";
}