How to Use Unrar Directly From PHP
PHP web applications can invoke unrar directly, either
by executing the command-line utility through system execution functions
or by using the official PECL extension. This article explains both
implementation methods, configuration prerequisites, and the security
measures required to safely extract RAR archives in a web
environment.
Method 1: The PECL RAR Extension
The cleanest and most secure approach is using the native PECL
rar extension, which embeds the UnRAR library directly into
the PHP runtime. This eliminates the need to execute shell commands.
- Installation: Install the extension via PECL or
your system package manager (e.g.,
pecl install rar). Ensureextension=rar.sois enabled in yourphp.ini. - Implementation: Use the
RarArchiveclass to inspect and extract contents:
$archive = RarArchive::open('/path/to/archive.rar');
if ($archive === false) {
die("Failed to open archive.");
}
$entries = $archive->getEntries();
foreach ($entries as $entry) {
$entry->extract('/path/to/destination/');
}
$archive->close();This approach bypasses system execution constraints and operates entirely within PHP memory and file system streams.
Method 2: System Execution Functions
If the PECL extension is not an option, you can invoke the system's
unrar binary directly using execution functions like
exec(), shell_exec(), or
proc_open().
- Prerequisites:
- The
unrarbinary must be installed on the host operating system (e.g.,apt install unrar). - Functions like
execmust not be listed underdisable_functionsinphp.ini.
- The
- Implementation:
$archivePath = escapeshellarg('/path/to/archive.rar');
$destination = escapeshellarg('/path/to/destination/');
// "x" extracts with full path structure; "-o+" overwrites existing files
$command = "unrar x -o+ {$archivePath} {$destination}";
exec($command, $output, $returnCode);
if ($returnCode === 0) {
echo "Extraction successful.";
} else {
echo "Extraction failed with code: " . $returnCode;
}Essential Considerations and Security
When invoking unrar from a web application, several
factors must be handled:
- File Permissions: The web server user (such as
www-dataornginx) must have read permissions for the RAR file, execute permissions for theunrarbinary, and write permissions for the destination directory. - Command Injection: Always wrap file paths and
arguments in
escapeshellarg()if using shell functions to prevent malicious command execution from user-supplied file names. - Decompression Bombs (Zip Bombs): Maliciously
crafted small archives can unpack into hundreds of gigabytes, consuming
disk space and CPU. Implement limits on maximum extracted file size and
enforce execution timeouts via
set_time_limit(). - Path Traversal: Validate the destination directory
to ensure archives containing relative paths (such as
../../) do not overwrite sensitive system files outside the designated target folder.