PHP gzuncompress with file read and write errors

我怕爱的太早我们不能终老 提交于 2019-12-24 03:15:19

问题


I have a function that keeps track of events that happen through out the script. In an effort to use my resources effectively, I decided to compress the data that it generates. However, I keep getting this error:

Unknown error type: [2] gzuncompress() [function.gzuncompress]: data error

Here's the function:

function eventlog($type, $message){
    // Types: account,run,queue,system
    // Set up file name/location
    $eventfile = '/myprivatedirectory/'.date('Ymd').$type.'.log';

    if(file_exists($eventfile)){
        while(!is_writable($eventfile)){clearstatcache();}

        $fh_log = fopen($eventfile,'r+');
        flock($fh_log, LOCK_EX);
        $logcontents = gzuncompress(fread($fh_log,filesize($eventfile)));

        rewind($fh_log);
        ftruncate($fh_log, 0);

        $logcompressed = gzcompress($logcontents.$message."\n");
        fwrite($fh_log,$logcompressed);
        flock($fh_log, LOCK_UN);
        fclose($fh_log);
    } else {
        $fh_log = fopen($eventfile,'w');
        flock($fh_log, LOCK_EX);
        $logcompressed = gzcompress($message."\n");
        fwrite($fh_log,$logcompressed);
        flock($fh_log, LOCK_UN);
        fclose($fh_log);
    }
}

So everyday, at midnight, a new error log is created as any of the above events occur (account,run,queue,system), otherwise each new event is appended to the respectful log file.

I would love to keep the compression, but I can not keep having these errors, can anyone please help? Thanks in advance.


回答1:


I think the implementation is all wrong i would not advice you to gzcompress($message."\n"); every message ...

I think what you should do is that at the end of the day you can compress the whole log file which is more efficient

Save your information using

  file_put_contents

At the end of the day

$eventfile = '/myprivatedirectory/'.date('Ymd').$type.'.log';
$eventfileCompressed = '/myprivatedirectory/'.date('Ymd').$type.'.gz';
$gz = gzopen($eventfileCompressed ,"w9");
gzwrite($gz, file_get_contents($eventfile));
gzclose($gz);

To read the file

$zd = gzopen($eventfileCompressed,"r");
$zr = gzread($zd,$fileSize);
gzclose($zd);

This approach would save you more processing power



来源:https://stackoverflow.com/questions/9768237/php-gzuncompress-with-file-read-and-write-errors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!