总结
豆包 AI 助手文章总结

PHP 如何与 shell 命令互动?

WBOY
发布: 2024-08-27 11:33:03
原创
721人浏览过

php 与 shell 命令交互方法:exec() 函数:执行命令并获取输出。shell_exec() 函数:在独立 shell 进程中执行命令。popen() 函数:通过管道与命令双向通信。proc_open() 函数:提供了更高级的控制,可指定命令流。

PHP 如何与 shell 命令互动?

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: $other\n";
}
登录后复制

以上就是PHP 如何与 shell 命令互动?的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
豆包 AI 助手文章总结
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号