File compression using PHP
Installation
Unix:
Bzip2 support in PHP is not enabled by default. You will need to use the --with-bz2[=DIR] configuration option when compiling PHP to enable bzip2 support.
Windows:
Open your php.ini . Activate the entry "extension=php_bz2.dll" by removing ";" in front of the line. Restart the web server.
You can compress a string using bzcompress function .
mixed bzcompress ( string source [, int blocksize ] )
source
The string to compress.
blocksize
should be a number from 1 to 9 with 9 giving the best and slowest compression and 1 being the largest and fastest . blocksize defaults to 4.
<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>
You can uncompress a string using
bzdecompress
function .
mixed bzdecompress ( string source )
source
The string to decompress.
<?php
$start_str = "This is not an honest face?" ;
$bzstr = bzcompress ( $start_str );
echo "Compressed String: " ;
echo $bzstr ;
echo "\n<br />\n" ;
$str = bzdecompress ( $bzstr );
echo "Decompressed String: " ;
echo $str ;
echo "\n<br />\n" ;
?>
The most important is whether we can compress and decompress a file. To compress a file we have to open a file handle using bzopen() and then write into it using bzwrite() function.
compress a file
<?php $file_name = "data.txt";
$file_pointer = fopen($file_name, "r");
//Open the file in readonly mode,
//check if you read permission in unix
$file_read = fread($file_pointer, filesize($file_name));
// Reading the file contents, through the pointer
fclose($file_pointer);
// close the file
$filename = "testfile.bz2";
// open zip file for writing
$bz = bzopen($filename, "w");
// write string to file
bzwrite($bz, $file_read);
// close file
bzclose($bz);
?>
To decopress the file we have to open the zipped fille again using bzopen() and read the content using bzread(). Then write the content again to another file using fwrite().
<?php
$zip_filename = "testfile.bz2";
// open zip file for writing
$bz = bzopen($zip_filename, "r");
// write string to file
$str=bzread($bz);
// close file
bzclose($bz);
// Now open the file where the unzipped content will be stored
$file_name = "data1.txt";
$file_pointer = fopen($file_name, "w+");
//"w+" is the write mode, or the action we're going to perform on the file
//mode clears the existing file content to 0 bytes
fwrite($file_pointer, $str);
// write content of the unzipped file
fclose($file_pointer);
print "data unzipped to file successfully";
?>
This is basics of compressing and decompressing a file in PHP. Hope you have enjoyed the tutorial. Thank You.
Back to Tutorial Index page