Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract bz2 file in php

Tags:

php

extract

bzip2

I have exported an SQL file from a database by using phpmyadmin. The file is named final.sql.bz2 and then I uploaded it onto my Live Server.

The question is, how could I extract that file by using PHP code? I tried to search for that on google, but not getting any result. How could I unzip it?

like image 226
Mark Richards Avatar asked Oct 26 '25 14:10

Mark Richards


2 Answers

You should use the bzip function from PHP not the zip functions they are different.

http://php.net/manual/en/book.bzip2.php

Or if its possible you can use exec to execute the bunzip2 command to extract your file from your archive:

bunzip2 [DATEI].bz2
like image 77
René Höhle Avatar answered Oct 29 '25 04:10

René Höhle


I needed to extract bz2 in shared hosting where tar couldnt help me to extract (got error with bzip2 and lbzip2, and I could not install anything or do sudo...)

I solved it by creating a php file and run it from command line (of course you can modify the script to use it online too).

bunzip2.php

<?php
function decompress($data)
 {
     // Decompress the file
     if (@file_exists($data)) {
         $bz = bzopen($data, 'r');
         $uncompressed = '';
         // Read the uncompressed data.
         while (!feof($bz)) {
             $uncompressed .= bzread($bz, 4096);
         }
         // Close the Bzip2 compressed file and write
         // the data to the uncompressed file.
         bzclose($bz);
         if (stripos($data, '.tbz2') !== false) {
             $newFile = str_replace('.tbz2', '.tar', $data);
         } else {
             if (stripos($data, '.tbz') !== false) {
                 $newFile = str_replace('.tbz', '.tar', $data);
             } else {
                 $newFile = str_replace('.bz2', '', $data);
             }
         }
         file_put_contents($newFile, $uncompressed);
         return $newFile;
         // Else, decompress the string
     } else {
         return bzdecompress($data);
     }
 }

decompress($argv[1]);
?>

php bunzip2.php my.tar.bz2

(I just searched for bz2+php on github, I did not check the code in detail but it does the work ;)

like image 20
MrSimpleMind Avatar answered Oct 29 '25 04:10

MrSimpleMind



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!