php实现cmd
PHP 执行 CMD 命令的方法
在 PHP 中可以通过多种方式执行命令行(CMD)指令,以下是几种常见方法:
使用 exec() 函数
exec() 执行外部命令并返回最后一行输出结果:
$output = exec('dir', $fullOutput, $returnStatus);
print_r($output); // 最后一行输出
print_r($fullOutput); // 完整输出数组
echo $returnStatus; // 返回状态码
使用 shell_exec() 函数
获取命令执行的完整输出字符串:
$output = shell_exec('ipconfig /all');
echo $output;
使用 system() 函数
直接输出命令执行结果并返回最后一行:
$lastLine = system('ping 127.0.0.1', $returnCode);
echo "Return code: $returnCode";
使用 passthru() 函数
直接输出原始二进制结果(适用于图像/文件处理):
passthru('ffmpeg -i input.mp4 output.avi', $returnCode);
使用 proc_open() 高级控制
实现进程管道交互:
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'] // stderr
];
$process = proc_open('cmd', $descriptors, $pipes);
if (is_resource($process)) {
fwrite($pipes[0], '命令输入');
fclose($pipes[0]);
echo stream_get_contents($pipes[1]);
fclose($pipes[1]);
$returnValue = proc_close($process);
}
安全注意事项
- 永远不要直接传递用户输入到命令行:
// 危险示例 exec($_GET['cmd']);
// 安全做法 $allowedCommands = ['ls', 'date']; if (in_array($_GET['cmd'], $allowedCommands)) { exec(escapeshellcmd($_GET['cmd'])); }

2. Windows 系统注意路径转义:
```php
$dir = escapeshellarg('C:\Program Files');
exec("dir {$dir}");
常见应用场景
- 批量文件处理(如压缩/转换)
- 服务器状态监控(内存/磁盘检查)
- 后台任务调度
- 调用外部程序(如ImageMagick/FFmpeg)
通过合理选择上述函数,可以实现从简单到复杂的命令行交互需求。






