How can I extract or uncompress gzip file using php?
Try this found here
//This input should be from somewhere else, hard-coded in this example
$file_name = '2013-07-16.dump.gz';
// Raising this value may increase performance
$buffer_size = 4096; // read 4kb at a time
$out_file_name = str_replace('.gz', '', $file_name);
// Open our files (in binary mode)
$file = gzopen($file_name, 'rb');
$out_file = fopen($out_file_name, 'wb');
// Keep repeating until the end of the input file
while (!gzeof($file)) {
// Read buffer-size bytes
// Both fwrite and gzread and binary-safe
fwrite($out_file, gzread($file, $buffer_size));
}
// Files are done, close files
fclose($out_file);
gzclose($file);
How can I unzip a .gz file with PHP?
Download the Unzip library
and include or autoload
the unzip
library
$this->load->library('unzip');
PHP: How to uncompress GZ to a string?
You should be able to do it with the gzdecode
function from the Zlib library.
$uncompressedXML = gzdecode(file_get_contents($url));
More about gzdecode() from the PHP Docs.
However, there is even an easier way, and it's by using a compression wrapper.
$uncompressedXML= file_get_contents("compress.zlib://{$url}");
Or even better:
$xmlObject=simplexml_load_file("compress.zlib://{$url}");
Don't forget to install and enable Zlib on your development/production server.
Unpack large files with gzip in PHP
gzfile() is a convenience method that calls gzopen, gzread, and gzclose.
So, yes, you can manually do the gzopen and gzread the file in chunks.
This will uncompress the file in 4kB chunks:
function uncompress($srcName, $dstName) {
$sfp = gzopen($srcName, "rb");
$fp = fopen($dstName, "w");
while (!gzeof($sfp)) {
$string = gzread($sfp, 4096);
fwrite($fp, $string, strlen($string));
}
gzclose($sfp);
fclose($fp);
}
How can I read a .tar.gz file with PHP?
You can do this with the PharData
class:
// Example: list files
$archive = new PharData('/some/file.tar.gz');
foreach($archive as $file) {
echo "$file\n";
}
This even works with the phar://
stream wrapper:
$list = scandir('phar:///some/file.tar.gz');
$fd = fopen('phar:///some/file.tar.gz/some/file/in/the/archive', 'r');
$contents = file_get_contents('phar:///some/file.tar.gz/some/file/in/the/archive');
If you don't have Phar, check the PHP-only implementation, or the pecl extension.
Unzip a file with php
I can only assume your code came from a tutorial somewhere online? In that case, good job trying to figure it out by yourself. On the other hand, the fact that this code could actually be published online somewhere as the correct way to unzip a file is a bit frightening.
PHP has built-in extensions for dealing with compressed files. There should be no need to use system
calls for this. ZipArchive
docs is one option.
$zip = new ZipArchive;
$res = $zip->open('file.zip');
if ($res === TRUE) {
$zip->extractTo('/myzips/extract_path/');
$zip->close();
echo 'woot!';
} else {
echo 'doh!';
}
Also, as others have commented, $HTTP_GET_VARS
has been deprecated since version 4.1 ... which was a reeeeeally long time ago. Don't use it. Use the $_GET
superglobal instead.
Finally, be very careful about accepting whatever input is passed to a script via a $_GET
variable.
ALWAYS SANITIZE USER INPUT.
UPDATE
As per your comment, the best way to extract the zip file into the same directory in which it resides is to determine the hard path to the file and extract it specifically to that location. So, you could do:
// assuming file.zip is in the same directory as the executing script.
$file = 'file.zip';
// get the absolute path to $file
$path = pathinfo(realpath($file), PATHINFO_DIRNAME);
$zip = new ZipArchive;
$res = $zip->open($file);
if ($res === TRUE) {
// extract it to the path we determined above
$zip->extractTo($path);
$zip->close();
echo "WOOT! $file extracted to $path";
} else {
echo "Doh! I couldn't open $file";
}
How do you create a .gz file using PHP?
The other answers here load the entire file into memory during compression, which will cause 'out of memory' errors on large files. The function below should be more reliable on large files as it reads and writes files in 512kb chunks.
/**
* GZIPs a file on disk (appending .gz to the name)
*
* From http://stackoverflow.com/questions/6073397/how-do-you-create-a-gz-file-using-php
* Based on function by Kioob at:
* http://www.php.net/manual/en/function.gzwrite.php#34955
*
* @param string $source Path to file that should be compressed
* @param integer $level GZIP compression level (default: 9)
* @return string New filename (with .gz appended) if success, or false if operation fails
*/
function gzCompressFile($source, $level = 9){
$dest = $source . '.gz';
$mode = 'wb' . $level;
$error = false;
if ($fp_out = gzopen($dest, $mode)) {
if ($fp_in = fopen($source,'rb')) {
while (!feof($fp_in))
gzwrite($fp_out, fread($fp_in, 1024 * 512));
fclose($fp_in);
} else {
$error = true;
}
gzclose($fp_out);
} else {
$error = true;
}
if ($error)
return false;
else
return $dest;
}
UPDATE: Gerben has posted an improved version of this function that is cleaner and uses exceptions instead of returning false on an error. See https://stackoverflow.com/a/56140427/195835
How to read portions of a big gz file with PHP
Update; to get a specific part without a while loop
$filename = "my_big_file.txt.gz";
$zd = gzopen($filename, "r");
fseek($zd, 1000000); # jump to a new position here
$readfile = gzread($zd,1000000);
//...process $readfile
gzclose($zd);
Example
A text file (test.txt)
Given is the following text file:
12345678
Gzip it
Gzip the text file with:
gzip test.txt
A new file is created: test.txt.gz
Demo
function getGzFileChunk(string $filename, int $start, int $end)
{
$zd = gzopen($filename, "r");
fseek($zd, $start);
$readfile = gzread($zd, $end);
gzclose($zd);
return $readfile;
}
var_dump(getGzFileChunk("test.txt.gz", 3, 2)); //output: 45
var_dump(getGzFileChunk("test.txt.gz", 1, 2)); //output: 23
var_dump(getGzFileChunk("test.txt.gz", 4, 2)); //output: 56
var_dump(getGzFileChunk("test.txt.gz", 6, 2)); //output: 78
var_dump(getGzFileChunk("test.txt.gz", 2, 2)); //output: 34
Old answer
Place the gzread
in a while loop, like so:
<?php
$filename = "my_big_file.txt.gz";
$zd = gzopen($filename, "r");
while($readfile = gzread($zd,1000000)) {
//...your process
}
gzclose($zd);
Related Topics
What Does the Percent Sign Mean in PHP
Differencebetween $_Server['Request_Uri'] and $_Get['Q']
How to Extract a String from Double Quotes
How to Get PHP, Symlinks and _File_ to Work Together Nicely
MySQL Innodb Engine in Laravel
How to Convert Multiple <Br/> Tag to a Single <Br/> Tag in PHP
Class 'App\Http\Controllers\Db' Not Found and I Also Cannot Use a New Model
Laravel Many to Many Self Referencing Table Only Works One Way
How to Insert into MySQL Using a Prepared Statement with PHP
Line Break Not Working When Writing to Text File in PHP
PHP Get How Many Days and Hours Left from a Date
How to See the Actual Xml Generated by PHP Soap Client Class
A _Construct on an Eloquent Laravel Model
Mysql_Connect (Localhost/127.0.0.1) Slow on Windows Platform