Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to check if gz file is corrupt?

Tags:

php

gzip

corrupt

Is there any way to detect if a gz file is corrupt in PHP?

I'm currently using http://www.php.net/manual/de/function.gzread.php#110078 to determine the file size and read the whole* file via

$zd = gzopen ( $file, "r" );
$contents = gzread ( $zd, $fzip_size );
gzclose ( $zd );

Unfortunately some gz files are corrupted and the last 4 bytes do not represent the real length of the gz file. As long as the number is negativ I'm able to tell that something is wrong, but sometimes it's positive (and very large) which leads to an out of memory error. How can I check in advance if the file is corrupted?

  • I'm reading the whole file because I found no working way to read the file line-by-line without knowing the size of the longest line - which led (in some case) to lines that were not complete.
like image 236
Hirnhamster Avatar asked Nov 24 '22 04:11

Hirnhamster


1 Answers

If you can use linux gzip command it will be very simply to find if file is wrong or not. gzip -t will display no message if file is valid.

if (`gzip -t $file 2>&1`) {
    echo "An error occured";
}
like image 177
Mariusz Avatar answered Dec 05 '22 09:12

Mariusz