php exec() 函数可用于调用外部函数并获取其输出。其语法为:exec(string $command, array &$output = null, int &$return_var = null) : bool。参数包括:$command(要执行的命令字符串)、$output(接收命令输出的引用变量数组)和 $return_var(接收命令返回代码的引用变量)。exec() 函数被广泛用于各种场景,例如执行系统命令或解析外部脚本或程序的输出。

如何使用 PHP 函数 exec() 调用外部函数并获取其输出
PHP 函数 exec() 允许您调用外部函数并在 PHP 脚本中获取其输出。它在各种情况下非常有用,例如:
语法:
立即学习“PHP免费学习笔记(深入)”;
exec(string $command, array &$output = null, int &$return_var = null) : bool
参数:
$command: 要执行的命令字符串。$output: 一个引用变量数组,用于接收命令的输出。$return_var: 一个引用变量,用于接收命令的返回代码。实例:
让我们创建一个 PHP 脚本来使用 exec() 函数获取当前工作目录列表:
<?php
// 执行 'ls' 命令
$output = array();
$return_var = 0;
exec('ls', $output, $return_var);
// 检查命令是否成功执行
if ($return_var === 0) {
// 循环遍历输出数组并打印每个文件
foreach ($output as $file) {
echo $file . "\n";
}
} else {
// 处理错误
echo "命令執行失敗。錯誤碼:$return_var";
}
?>输出:
main.php composer.json vendor/
注意:
exec() 函数不能用于执行 PHP 代码。要执行 PHP 代码,请使用 shell_exec 或 proc_open 函数。以上就是如何使用 PHP 函数调用外部函数并获取其输出的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号