当 exec、system 等函数被禁用时,可通过 PHP 内置的 proc_open 函数绕过限制。该函数直接调用底层 POSIX 接口创建进程,不经过系统命令解释器(如 /bin/sh),因此不受 disable_functions 列表约束。只需确保目标服务器支持该函数且具备执行权限即可。

为什么 proc_open 能绕过限制
disable_functions 机制通过拦截 PHP 内核中的特定函数名来阻止执行。而 proc_open 属于进程控制类函数,不在默认黑名单中。它允许开发者精确控制标准输入、输出和错误流的管道连接,适合需要捕获输出的场景。

使用 proc_open 时,需传入一个描述符映射数组,定义 stdin、stdout 和 stderr 的处理方式。例如,将 stdout 设为 'pipe' 可获取命令输出。相比 shell_exec,它能更好地处理二进制数据或长输出,避免缓冲区截断问题。
实现跨平台兼容的执行脚本
以下代码演示如何使用 proc_open 执行 Shell 脚本并捕获输出。适用于 Linux/Unix 环境,Windows 下需调整命令语法。

<?php
function safeExec($cmd, $args = []) {
if (!function_exists('proc_open')) {
return ['error' => 'proc_open not available'];
}
// 构建完整命令
$fullCmd = $cmd . ' ' . implode(' ', array_map('escapeshellarg', $args));
$descriptors = [
0 => ['pipe', 'r'], // stdin
1 => ['pipe', 'w'], // stdout
2 => ['pipe', 'w'] // stderr
];
$process = proc_open($fullCmd, $descriptors, $pipes);
if (!is_resource($process)) {
return ['error' => 'Failed to start process'];
}
// 关闭 stdin
fclose($pipes[0]);
// 读取输出
$output = stream_get_contents($pipes[1]);
fclose($pipes[1]);
$errors = stream_get_contents($pipes[2]);
fclose($pipes[2]);
$returnCode = proc_close($process);
return [
'output' => trim($output),
'error' => trim($errors),
'code' => $returnCode
];
}
// 示例:执行 ls -l /tmp
$result = safeExec('ls', ['-l', '/tmp']);
echo "Output: " . $result['output'] . "\n";
echo "Error: " . $result['error'] . "\n";
echo "Exit Code: " . $result['code'] . "\n";
运行上述代码将列出 /tmp 目录内容。若 disable_functions 包含 proc_open,则返回错误提示。成功时,输出字段包含命令结果,错误字段包含 stderr 信息,退出码反映执行状态。注意:生产环境中应替换为具体业务脚本路径,并添加权限校验逻辑。
代码先检查 proc_open 是否可用,然后构建命令参数。通过管道读取输出,接着关闭资源。若遇到权限拒绝,请检查 Web 用户(如 www-data)是否有执行权限。
处理特殊字符与注入风险
直接使用用户输入拼接命令会导致严重的安全漏洞。即使绕过了函数禁用,仍需对输入进行严格过滤。
建议始终使用白名单验证输入参数,避免直接拼接字符串。对于必须执行的动态命令,可使用 escapeshellarg 转义参数,但需注意这仅防止部分注入。最佳实践是预定义允许执行的脚本列表,并通过索引调用,而非传递任意命令字符串。