PHP中如何通过参数向量简单调用外部程序?
PHP参数向量调用外部程序的解决方案
有的,PHP 8.0 起官方新增了3个原生的参数向量版程序执行函数,普通场景直接用就行,完全不需要复杂的proc_open配置,也从根源上避免了命令注入风险:
execv():对应原exec()的功能,第一个参数传入可执行文件的绝对路径,第二个参数直接传参数数组,不需要做任何转义处理。
示例:// 等效于执行 /bin/ls -l "/path/with space/in it" execv('/bin/ls', ['-l', '/path/with space/in it'], $output, $exit_code);shell_execv():对应原shell_exec()的功能,直接返回命令执行的输出字符串,无需额外配置。systemv():对应原system()的功能,执行后直接打印输出内容,返回输出的最后一行字符串。
如果你的环境暂时不支持PHP 8.0,也可以基于PHP 7.4新增的proc_open参数向量特性,做一个极简封装就能用:
/** * 基于参数向量的外部程序调用封装 * @param string $bin 可执行文件绝对路径 * @param array $args 参数数组 * @param array|null $output 输出数组,下标0为stdout内容,下标1为stderr内容 * @param int|null $exit_code 程序退出码 * @return string|null 程序stdout输出内容 */ function simple_proc_call(string $bin, array $args, ?array &$output = null, ?int &$exit_code = null): ?string { $proc = proc_open([$bin, ...$args], [ 0 => ['file', '/dev/null', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w'], ], $pipes); if (!is_resource($proc)) { return null; } $stdout = trim(stream_get_contents($pipes[1])); $stderr = trim(stream_get_contents($pipes[2])); fclose($pipes[1]); fclose($pipes[2]); $exit_code = proc_close($proc); $output = [$stdout, $stderr]; return $stdout; }
封装后的函数用法和原生函数基本一致,参数不需要做任何转义,也不会触发shell解析,自然不会存在命令注入风险。
内容的提问来源于stack exchange,提问作者DannyNiu
相关产品推荐
相关产品推荐

