Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP rar://
The RAR (Roshal Archive) is a file compression format that supports error recovery and file spanning. PHP supports the use of .RAR files as IO streams through the rar:// stream wrapper.
The rar:// wrapper takes the relative or absolute URL encoded path to the RAR archive, with an optional asterisk (*) or hash (#) and an optional URL encoded entry name as stored in the archive. This wrapper can open both files and directories.
Installation Required: This wrapper is not enabled by default. You must install the RAR extension from PECL (PHP Extension Community Library) using:pecl install rar
Syntax
rar://<url encoded archive name>[*][#[<url encoded entry name>]]
RAR Context Options
| Option | Description |
|---|---|
open_password |
The password used to encrypt the headers of the archive, if any |
file_password |
The password used to encrypt a file, if any. If headers are encrypted, this option is ignored in favor of open_password |
volume_callback |
A callback to determine the path of missing volumes |
Example
Here's how to read a file from a RAR archive using the rar:// wrapper −
<?php
// Open a file from RAR archive
$file = fopen('rar://archive.rar#file.txt', 'r');
if ($file) {
$content = fread($file, filesize('rar://archive.rar#file.txt'));
echo $content;
fclose($file);
} else {
echo "Failed to open file from RAR archive";
}
?>
Listing Archive Contents
To list the contents of a RAR archive, use the hash (#) symbol to access the root directory −
<?php
$handle = opendir('rar://archive.rar#');
if ($handle) {
while (($entry = readdir($handle)) !== false) {
echo $entry . "<br>";
}
closedir($handle);
}
?>
Key Points
- If the pound sign (#) and entry name are omitted, the root of the archive is displayed
- When using RecursiveDirectoryIterator, the number sign must be included in the URL
- URL encoding is required for archive and entry names containing special characters
- The wrapper supports both reading files and listing directories within RAR archives
Conclusion
The rar:// stream wrapper provides seamless access to RAR archives in PHP, allowing you to read files and list directories as if they were part of the regular filesystem. Remember to install the RAR extension from PECL before using this functionality.
