Unzip a file with php

Unzip a file with php

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Why system('unzip $file') Breaks with User Input

Using system('unzip File.zip') works because the shell interprets the command literally, extracting a file named exactly File.zip from the current directory. It is a straightforward mechanism for executing external binaries. However, when you replace that literal string with a variable derived from user input, such as $master = $_GET["master"], the behavior changes entirely due to how the shell parses arguments and handles special characters.

The core issue isn't missing flags or syntax errors in the PHP code itself; it is the interaction between the variable expansion and the shell interpreter. When you execute system('unzip $master.zip'), PHP passes the string "unzip [variable_contents].zip" to the OS. If $_GET["master"] contains a space, a quote, or a dash, the command breaks immediately because the shell treats these as argument separators or operators rather than part of a filename.

For example, if a user submits foo bar, the resulting command becomes unzip foo bar.zip. The shell interprets this as two arguments to unzip: foo and bar.zip. Since foo does not exist as a directory or file context for the unzip utility in this manner, the operation fails. Even worse, if the input contains characters like ', ", ;, or |, an attacker could potentially inject arbitrary shell commands before the unzip command executes, leading to Remote Code Execution (RCE).

The Safe Approach: Escaping Arguments

To make this work dynamically, you must ensure that the filename is treated as a single atomic argument and that any special characters are neutralized. The escapeshellarg() function was introduced specifically for this scenario. It wraps the string in single quotes and escapes any internal single quotes, ensuring the shell sees exactly one argument regardless of its content.

Here is how to refactor the code safely:

$master = $_GET["master"];
$safePath = escapeshellarg($master . '.zip');
exec("unzip " . $safePath);

By using escapeshellarg(), even if $master contains spaces or quotes, the shell receives a single string like 'foo bar.zip'. This prevents argument splitting and neutralizes most injection vectors. Additionally, switching from system() to exec() (or capturing output with shell_exec()) is often preferable when you need to handle the return value or suppress output clutter, though system() is acceptable if you only care about exit codes.

The Better Approach: Avoiding Shell Execution Entirely

While escaping arguments solves the immediate crash, relying on the shell (system, exec, shell_exec) remains an architectural anti-pattern in modern PHP development. It introduces overhead for spawning processes and leaves your application vulnerable to edge cases that escape functions might miss.

Laravel provides a robust way to handle file operations without invoking the system shell. Using the built-in ZipArchive class allows you to extract files directly in memory or on disk, completely bypassing the risks associated with command-line parsing. This method is faster, more secure, and platform-independent.

$master = $_GET["master"];
$path = $master . '.zip';

if (!file_exists($path)) {
    throw new InvalidArgumentException("File not found.");
}

$zip = new ZipArchive();
if ($zip->open($path) === false) {
    throw new RuntimeException("Unable to open ZIP archive.");
}

// Extract to a specific directory, e.g., public/uploads/extracted
$targetDir = 'public/uploads';
$zip->extractTo($targetDir);
$zip->close();

This approach validates the file existence, opens the archive using native PHP functions, and extracts contents to a controlled directory. It eliminates the risk of shell injection entirely and ensures that only valid ZIP structures are processed. If you are working within the Laravel framework, this pattern aligns perfectly with how the framework handles file system interactions securely.

Trade-offs and Considerations

There is a specific case where ZipArchive might not suffice: when the source code is not PHP or requires specific command-line flags (e.g., extracting to a relative path based on the filename). However, for standard extraction tasks, avoiding the shell is always the superior choice. It removes the dependency on the operating system's unzip binary being present and configured correctly, ensuring consistent behavior across Linux, Windows, and macOS servers.

If you must stick with the command line for legacy reasons or specific flags, remember that escapeshellarg() is non-negotiable. Never concatenate user input directly into a shell command string without sanitization. The difference between a working script and a compromised server often lies in how a single variable is handled before it reaches the OS.

Our network