How to make PHP unrar and unzip recursively folder with files?

Simple task - unzip zip archive and unrar rar archive. With zip it's all easy, just some basic PHP default ZipArchive class and you have it, but with rar - why to make things more complicated?






Recursively extract ZIP archives

So with zip files you just have to get new ZipArchive object, use simple "open" php function to get your zip archive opened, and show where to extract with "extractTo" and of course just not to forget to clear your memory with "close" command. That's it. Nice and easy.

$zip = new ZipArchive;
$res = $zip -> open("$local_file/$item");
if ($res === TRUE) {
    $zip -> extractTo($local_file);
    $zip -> close();
} else {
    $zip -> close();
    echo "Unable to unzip your zip archive.";
}

Recursively extract RAR archives

Now let's try to do it with rar archive. Firstly I can't think for what reason php developers made it not same like with zip archive? Why not to have such function as "extractTo"? So it would be easy, firstly you could find out the extension of archive and just create ZipArchive or RarArchive object and just use same functions. These are only my own wishes.. In the real world to extract rar archive I had to make something like this:

Step 1 - install rar extenstion to your server

I had to have rar extension installed in my server. It's all written here: http://php.net/manual/en/rar.installation.php

Step 2 - use RarArchive (PHP class)

Use php class called RarArchive.

$rar = RarArchive::open("$local_file/$item");

if ($rar !== FALSE) {
    $enteries = $rar -> getEntries();
    foreach ($enteries as $entry) {
         $entry -> extract($local_file);
    }
    $rar -> close();
} else {
    $rar -> close();
    exho "Unable to unrar your rar archive.";
}

Conclusion

Both archives can be extracted with php, but as you see it is easier to use zip format, than rar because with rar you have to install extra software to your server.

1 comment:

You can ask IT questions in comments!