PHP执行系统命令的5种核心函数
- 
exec()
执行命令并返回最后一行输出:$output = []; $lastLine = exec('dir C:\', $output, $returnCode); print_r($output); // 输出所有行 echo "返回值: $returnCode"; // 0表示成功 - 
system()
直接输出命令结果并返回最后一行:$lastLine = system('ping 127.0.0.1', $returnCode); echo "返回值: $returnCode"; - 
shell_exec()
返回命令的完整输出(字符串形式):$result = shell_exec('ipconfig'); echo "<pre>$result</pre>"; - 
passthru()
直接输出原始二进制流(适合处理图像/压缩文件):passthru('7z a archive.rar file.txt', $returnCode); - 
反引号操作符
功能同shell_exec():$files = `dir /B`; // 简写形式 echo $files;
 
关键安全规范(避免命令注入攻击)
永远不要直接执行用户输入! 以下为防护措施:
// 危险示例(绝对禁止!)
$userInput = $_GET['cmd'];
system($userInput); // 用户可输入 rm -rf / 等恶意命令
// 正确做法1:使用白名单过滤
$allowedCommands = ['ping', 'dir', 'ipconfig'];
if (in_array($_GET['cmd'], $allowedCommands)) {
    system(escapeshellcmd($_GET['cmd']));
}
// 正确做法2:转义参数
$fileName = $_GET['file'];
$safeCmd = 'dir ' . escapeshellarg($fileName); // 自动添加引号
system($safeCmd);
必须遵守的安全原则:
- 使用 
escapeshellarg()和escapeshellcmd()处理所有动态参数 - 以最低权限运行PHP(避免使用root账户)
 - 禁用敏感函数(在
php.ini中设置disable_functions=exec,system,...) - 对用户输入进行白名单验证
 
Windows系统注意事项
- 路径使用反斜杠:
exec('cd C:\\Windows && dir'); // 双反斜杠转义 - 执行批处理文件:
system('cmd /c backup.bat', $code); // /c 执行后关闭CMD - 处理中文乱码:
chcp 65001 > nul'); // 切换UTF-8编码 exec('chcp 65001 > nul && dir'); 
最佳实践建议
- 
优先使用PHP内置函数
- 文件操作:用
scandir()代替dir/ls - 删除文件:用
unlink()代替del - 压缩解压:用ZipArchive类代替调用WinRAR
 
 - 文件操作:用
 - 
记录日志
$log = date('[Y-m-d H:i:s]') . " 执行命令: $safeCmd\n"; file_put_contents('command.log', $log, FILE_APPEND); - 
设置超时
set_time_limit(30); // 限制最长执行30秒 exec('long_running_task.exe'); 
典型应用场景
- 自动化备份
shell_exec('mysqldump -u user -p123 db > C:\backup.sql'); - 系统监控
$cpu = shell_exec('wmic cpu get loadpercentage /Value'); - 批量文件处理
exec('magick convert *.jpg -resize 800x600 output\', $output); 
重要警告:
在Web环境中执行系统命令是高风险操作,除非绝对必要且已做好安全防护,否则应避免使用,多数操作可通过PHP原生函数实现,更安全高效。
引用说明:
- PHP官方安全指南:https://www.php.net/manual/en/security.variables.php
 - OWASP命令注入防护:https://cheatsheetseries.owasp.org/cheatsheets/OS_Command_Injection_Defense_Cheat_Sheet.html
 - Windows命令行文档:https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/windows-commands
 
原创文章,发布者:酷番叔,转转请注明出处:https://cloud.kd.cn/ask/9382.html