passthru / escapeshellcmd

passthru(string $command, ?int &$result_code = null): ?false; escapeshellcmd(string $command): string

passthru 把子进程输出原样直出(无返回串,适合二进制数据);escapeshellcmd 就地转义命令串元字符,与 escapeshellarg 的「整值加引号」互补——转义函数存在的原因正是 PHP 默认走 shell。

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void) {
    /* execvp(argv) 直接把参数数组交给内核——没有 shell 解析文本,
       参数里的 ';' 只是普通数据 */
    int p[2];
    if (pipe(p) != 0) return 1;
    pid_t pid = fork();
    if (pid == 0) {
        dup2(p[1], 1);
        close(p[0]); close(p[1]);
        char *argv[] = {"echo", "a;b", NULL};
        execvp(argv[0], argv);
        _exit(127);
    }
    close(p[1]);
    char buf[64];
    ssize_t n = read(p[0], buf, sizeof buf - 1);
    if (n > 0) buf[n] = '\0'; else buf[0] = '\0';
    close(p[0]);
    fputs(buf, stdout);
    int status = 0;
    waitpid(pid, &status, 0);
    printf("exit code: %d\n", WEXITSTATUS(status));
    return 0;
}
输出
a;b
exit code: 0

C++ C++26

C++26
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>

int main() {
    // std::system() 会经过 /bin/sh 才需要转义;
    // fork + execlp 把 argv 直接交给内核——无 shell,无需转义
    int p[2];
    if (pipe(p) != 0) return 1;
    pid_t pid = fork();
    if (pid == 0) {
        dup2(p[1], 1);
        close(p[0]); close(p[1]);
        execlp("echo", "echo", "a;b", (char *)nullptr);
        _exit(127);
    }
    close(p[1]);
    char buf[64];
    ssize_t n = read(p[0], buf, sizeof buf - 1);
    if (n > 0) buf[n] = '\0'; else buf[0] = '\0';
    close(p[0]);
    std::cout << buf;
    int status = 0;
    waitpid(pid, &status, 0);
    std::cout << "exit code: " << WEXITSTATUS(status) << "\n";
    return 0;
}
输出
a;b
exit code: 0

C# v11.0.100

v11.0.100
// ProcessStartInfo 直接运行程序:中间没有 cmd.exe,
// 带 ';' 的参数完全不需要转义
using System.Diagnostics;

var psi = new ProcessStartInfo("echo") { RedirectStandardOutput = true };
psi.ArgumentList.Add("a;b");
using var p = Process.Start(psi)!;
Console.Write(p.StandardOutput.ReadToEnd());
p.WaitForExit();
Console.WriteLine("exit code: " + p.ExitCode);
输出
a;b
exit code: 0

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"os/exec"
)

func main() {
	// exec.Command 收的是 argv,不是命令行字符串:没有 shell 解析文本,
	// 参数里的 ';' 只是普通数据
	out, err := exec.Command("echo", "a;b").Output()
	if err != nil {
		panic(err)
	}
	fmt.Print(string(out))
	fmt.Println("errored: false")
}
输出
a;b
errored: false

Java v27.0.1

v27.0.1
public class Main {
    public static void main(String[] args) throws Exception {
        // ProcessBuilder 收的是 argv,不是命令行字符串:没有 shell 解析
        // 文本,参数里的 ';' 只是普通数据
        Process p = new ProcessBuilder("echo", "a;b").start();
        System.out.print(new String(p.getInputStream().readAllBytes()));
        System.out.println("exit code: " + p.waitFor());
    }
}
输出
a;b
exit code: 0

JavaScript v26.13.1

v26.13.1
// execFile 收参数数组:中间没有 shell,';' 只是普通数据
const { execFile } = require("child_process");
execFile("echo", ["a;b"], (err, stdout) => {
    console.log(stdout.trimEnd());
    console.log("errored:", err !== null);
});
输出
a;b
errored: false

PHP v8.6.0

v8.6.0
// escapeshellarg 把「整个值」用单引号包成一个不可再分的参数
//(向命令行里插入用户数据时的标准做法)
echo escapeshellarg('a;b c'), "\n";
// escapeshellcmd 就地转义元字符、保留命令结构:用于你自己拼好的命令串
//(防尾随注入),不用于不可信数据
echo escapeshellcmd('echo "a;b" | cat'), "\n";
// passthru 把子进程输出原样直出(没有返回串)——
// 所以适合二进制数据(图片、压缩包)
passthru('printf "raw\tbytes\n"');
输出
'a;b c'
echo "a\;b" \| cat
raw	bytes

Python v3.15.2

v3.15.2
import subprocess

# run() 传 argv 列表:中间没有 shell,';' 保持为普通数据
r = subprocess.run(["echo", "a;b"], capture_output=True, text=True)
print(r.stdout.strip())
print("exit code:", r.returncode)
输出
a;b
exit code: 0

Rust v1.99.1

v1.99.1
use std::process::Command;

fn main() {
    // Command::arg 把参数直接交给 execve:没有 shell 解析文本,
    // 参数里的 ';' 只是普通数据
    let out = Command::new("echo").arg("a;b").output().unwrap();
    print!("{}", String::from_utf8(out.stdout).unwrap());
    println!("errored: {}", !out.status.success());
}
输出
a;b
errored: false

TypeScript v26.13.1

v26.13.1
// execFile 收参数数组:中间没有 shell,';' 只是普通数据
import { execFile } from "child_process";
execFile("echo", ["a;b"], (err: Error | null, stdout: string) => {
    console.log(stdout.trimEnd());
    console.log("errored:", err !== null);
});
输出
a;b
errored: false

语言差异说明

c:execvp(argv) 直接把参数数组交给内核,不经 shell——参数里的 ';' 只是普通数据。对照组是 system()/popen():那条路走 /bin/sh -c,才需要转义(示例不走)。这正是「转义函数存在原因」的谱系:有 shell 才需要转义。

cpp:与 C 同构的两条路线并存:std::system/popen 走 shell(要转义),fork+execlp 不走(不用转义)——选路即选要不要转义。

csharp:ProcessStartInfo 默认不走 shell(UseShellExecute = false 时 ArgumentList 逐个传参、不经解析);要拼参数请用 ArgumentList 而不是 Arguments 字符串——后者会被 cmd 按空格解析,转义责任回到你身上。

go:exec.Command(name, args...) 不走 shell;要用 shell 特性(管道、通配、重定向)得显式调 sh -c——显式即自觉,注入面一目了然。

java:ProcessBuilder(String... command) 不走 shell;Runtime.exec(String) 那个按空格拆分的重载是历史坑(内部用 StringTokenizer),请永远用 ProcessBuilder。

javascript:child_process 里 exec/spawn 传字符串命令时走 shell,execFile/spawn 传参数数组时不走——PHP escapeshellarg 的对应物在这里不是「转义」,而是「改用 execFile」。

php:escapeshellarg 把整个值包进单引号变成一个不可再分的参数(向命令行插入用户数据的标准做法);escapeshellcmd 就地转义元字符、保留命令结构(给你自己拼好的命令串再过一道,防尾随注入)——arg 管「值」,cmd 管「串」,不是同一层问题。passthru 把子进程输出原样直出、无返回串,手册推荐它输出二进制数据(图片、压缩包)——exec 会把输出填进数组,二进制会损坏;第二参接收退出码。

python:subprocess.run([...]) 的 argv 列表不走 shell;传字符串命令(或 shell=True)才走 /bin/sh -c——转义需求只在后者出现,对应物是 shlex.quote。

rust:Command::arg 逐个传参不走 shell;要 shell 得显式 Command::new("sh").arg("-c")。

typescript:同 JavaScript(execFile 数组式调用)。

共性:转义函数的存在理由是「默认走 shell」——不走 shell 的语言连转义函数都没有。PHP 需要 escapeshellarg/escapeshellcmd 正因为 exec/passthru 家族默认 sh -c;现代实践是优先数组式调用(proc_open 数组命令,PHP 7.4+),让整个转义问题消失。