passthru / escapeshellcmd
passthru(string $command, ?int &$result_code = null): ?false; escapeshellcmd(string $command): string
passthru streams the child output straight through (no return string, fit for binary data); escapeshellcmd escapes metacharacters in a command string in place, complementing escapeshellarg's "wrap the whole value in quotes" - escaping functions exist precisely because PHP goes through the shell by default.
C C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void) {
/* execvp(argv) replaces the image directly - no shell ever parses the
text, so a ';' inside one argument stays literal data */
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
#include <cstdlib>
#include <iostream>
#include <sys/wait.h>
#include <unistd.h>
int main() {
// std::system() would route through /bin/sh and need escaping;
// fork + execlp passes argv straight to the kernel - no shell, no escaping
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
// ProcessStartInfo runs the file directly: no cmd.exe sits in between,
// so an argument with ';' needs no escaping at all
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
package main
import (
"fmt"
"os/exec"
)
func main() {
// exec.Command takes argv, not a command line: no shell parses the
// string, so a ';' in one argument stays literal data
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
public class Main {
public static void main(String[] args) throws Exception {
// ProcessBuilder takes argv, not a command line: no shell parses
// the text, so a ';' in one argument stays literal data
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
// execFile takes an argv array: no shell sits in between, so ';' is literal
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
// escapeshellarg wraps the WHOLE value in quotes: one indivisible argument
// (the safe choice for a value you insert into a command line)
echo escapeshellarg('a;b c'), "\n";
// escapeshellcmd escapes metacharacters in place but keeps the command
// structure: for command text you build yourself, not for untrusted values
echo escapeshellcmd('echo "a;b" | cat'), "\n";
// passthru streams the raw child output straight to the browser/stdout -
// no return string, which is why it suits binary data (images, archives)
passthru('printf "raw\tbytes\n"');
'a;b c' echo "a\;b" \| cat raw bytes
Python v3.15.2
import subprocess
# run() with an argv list: no shell sits in between, so ';' stays literal
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
use std::process::Command;
fn main() {
// Command::arg passes argv straight to execve: no shell parses the
// text, so a ';' in one argument stays literal data
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
// execFile takes an argv array: no shell sits in between, so ';' is literal
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
Language differences
c: execvp(argv) hands the argument array straight to the kernel, no shell in between - a ';' inside one argument stays plain data. The contrast is system()/popen(): that route goes through /bin/sh -c and WOULD need escaping (this example doesn't). This is the "why escaping functions exist" family tree: a shell is what makes escaping necessary.
cpp: two isomorphic routes coexist: std::system/popen go through the shell (escaping needed), fork+execlp don't (no escaping) - picking the route is picking whether you escape.
csharp: ProcessStartInfo bypasses the shell by default (with UseShellExecute = false, ArgumentList passes arguments one by one, unparsed); prefer ArgumentList over the Arguments string - the latter is parsed by cmd on spaces and the escaping burden returns to you.
go: exec.Command(name, args...) bypasses the shell; shell features (pipes, globs, redirection) require an explicit sh -c - explicitness is awareness, and the injection surface is plain to see.
java: ProcessBuilder(String... command) bypasses the shell; the Runtime.exec(String) overload that splits on spaces is a historical trap (it uses StringTokenizer internally) - always use ProcessBuilder.
javascript: in child_process, exec/spawn with a string command go through the shell, execFile/spawn with an argument array don't - the counterpart of PHP's escapeshellarg here is not "escaping" but "switch to execFile".
php: escapeshellarg wraps the whole value in single quotes into one indivisible argument (the standard move when inserting user data into a command line); escapeshellcmd escapes metacharacters in place while keeping the command structure (run your own assembled command string through it against trailing injection) - arg handles the "value", cmd handles the "string", they are different layers. passthru streams the child output raw with no return string, and the manual recommends it for binary data (images, archives) - exec fills output into an array and binary would corrupt; the second parameter receives the exit code.
python: subprocess.run([...]) with an argv list bypasses the shell; passing a string command (or shell=True) goes through /bin/sh -c - the escaping need only arises in the latter case, and its counterpart is shlex.quote.
rust: Command::arg passes arguments one by one without a shell; shell usage needs an explicit Command::new("sh").arg("-c").
typescript: same as JavaScript (the execFile array form).
common ground: the reason escaping functions exist is "the shell by default" - languages that bypass the shell have no escaping functions at all. PHP needs escapeshellarg/escapeshellcmd precisely because the exec/passthru family defaults to sh -c; the modern practice is to prefer the array form (proc_open with an array command, PHP 7.4+) and make the whole escaping problem disappear.