5

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.
Hirnhamster
  • 6,032
  • 7
  • 35
  • 65

1 Answers1

0

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";
}
Mariusz
  • 13
  • 2
  • `if ('gzip -t $file 2>&1')` in PHP will always return true. It's a string. – c-griffin Aug 26 '14 at 22:08
  • 2
    @c-griffin: `if` condition executes external program. The result is empty or not empty string. Notice that ` is not the same as ' which you used in your comment. Source: [link](http://php.net/manual/en/language.operators.execution.php) – Mariusz Aug 27 '14 at 07:57
  • Hmmm you're right! Sorry man, thought they were single quotes and didn't even know you could use ticks to run shell commands. – c-griffin Aug 27 '14 at 12:57