PHP.mk документација

gzread

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.gzread.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.gzread.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
gzread

Референца за `function.gzread.php` со подобрена типографија и навигација.

function.gzread.php

gzread

(PHP 4, PHP 5, PHP 7, PHP 8)

gzreadBinary-safe gz-file read

= NULL

gzread(resource $stream, int $length): string|false

gzread() чита до length Бинарно-безбедно читање на gz-датотека length бајти од дадениот покажувач на gz-датотека. Читањето престанува кога EOF се достигне, кое и да настапи прво.

Параметри

stream

Покажувачот на gz-датотека. Мора да биде валиден и да покажува на датотека успешно отворена од gzopen().

length

(некомпресирани) бајти се прочитани или

Вратени вредности

Бројот на бајти за читање. false при неуспех.

Дневник на промени

Верзија = NULL
7.4.0 Оваа функција враќа false при неуспех сега; претходно 0 .

Примери

Пример #1 gzread() example

<?php
// get contents of a gz-file into a string
$filename = "/usr/local/something.txt.gz";
$zd = gzopen($filename, "r");
$contents = gzread($zd, 10000);
gzclose($zd);
?>

Види Исто така

  • gzwrite() Податоците што се прочитани, или
  • gzopen() - Отвори gz-датотека
  • gzgets() - Бинарно-безбедно запишување на gz-датотека
  • gzgetss() Земи ред од покажувач на датотека
  • gzfile() Земи ред од покажувач на gz-датотека и отстрани ги HTML таговите
  • gzpassthru() Прочитај цела gz-датотека во низа

Белешки од корисници 9 белешки

Испринтај ги сите преостанати податоци на покажувач на gz-датотека
пред 13 години
Here is a function for returning the uncompressed filesize of a gzip file. The filesize is stored as a 32-bit integer in the end of the compressed file, that's how this function works. Additionally, this function checks to see if it's a real gzip compressed file before doing the work; if it isn't, then just like other gz- functions, it'll treat it just like a regular file and perform a normal filesize operation. Enjoy!

<?php

function gzfilesize($filename) {
  $gzfs = FALSE;
  if(($zp = fopen($filename, 'r'))!==FALSE) {
    if(@fread($zp, 2) == "\x1F\x8B") { // this is a gzip'd file
      fseek($zp, -4, SEEK_END);
      if(strlen($datum = @fread($zp, 4))==4)
        extract(unpack('Vgzfs', $datum));
    }
    else // not a gzip'd file, revert to regular filesize function
      $gzfs = filesize($filename);
    fclose($zp);
  }
  return($gzfs);
}

?>
Азот
пред 8 години
Be careful when reading data in a loop. gzread() behaves a little differently than bzread() or fread(), it does NOT return false when reading past the end of stream. It instead returns an empty string.

So a loop like:
$handle = gzopen($file);
while (false !== $chunk = gzread($handle, $bytes)) {
   //...
}

will loop indefinitely.
waldermort на gmail точка com
пред 16 години
<?php
//Using FTP Download a gzip file on current date from a remote server
//The gzip files are extracted
function parse_rawlist( $array )
{
    $i=0;
    foreach($array as $curraw)
    {
        $struc = array();
        $current = preg_split("/[\s]+/",$curraw,9);

        $struc['perms']      =     $current[0];
        $struc['number']     =     $current[1];
        $struc['owner']     =     $current[2];
        $struc['group']      =     $current[3];
        $struc['size']         =     $current[4];
        $struc['month']      =     $current[5];
        $struc['day']        =     $current[6];
        $struc['time']      =     $current[7];
        $struc['zfile_name']      =     $current[8];
     $structure[$i]      =     $struc;
    $i++;
    }
   return $structure;

}
ini_set('memory_limit', '100M');

//Give FTP Information Here
//------------------------------------------------------------
$ftp_server     =     "example.com";
$ftp_user_name    =    "example";
$ftp_user_pass    =    "test";
//------------------------------------------------------------
//------------------------------------------------------------
$local_path     =    '/opt/lampp/htdocs/sample/test.gz';//Local Path
$server_path     =     'outgoing/folder/';//Remote Sever Path
//------------------------------------------------------------

$conn_id = ftp_connect($ftp_server,21);
if($conn_id)
{
    echo "Successfully connected";
}
  
$login_result     =     ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
ftp_chdir($conn_id, $server_path);//Change Current Working Directory
$file_list     =    ftp_rawlist($conn_id,".");
$zip_details    =    parse_rawlist($file_list);
set_time_limit(1000); 
$curr_date    =    strtotime(date("F d Y"));
for($i=0;$i<count($zip_details);$i++)
{
    $fname        =    $zip_details[$i]['zfile_name'];    
    $mod_date1    =    $zip_details[$i]['month']." ".$zip_details[$i]['day']." ".date("Y");    
    $mod_date    =    strtotime($mod_date1);//File Modified Date
    if($mod_date == $curr_date)//If modified date equals current date
    {
        $local_file    =    $fname;
        $server_file    =    $fname;
        if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) 
        {
        
            echo "<br/>Successfully written to $local_file\n";
        } 
        else 
        {
            echo "<br/>There was a problem\n";
        }
        if(file_exists($local_file))
        {
            $fzip_size    =    $zip_details[$i]['size'];    
            $filename    =    $local_file;
            $ext        =    pathinfo($filename,PATHINFO_EXTENSION);    
            $file_name    =    pathinfo($filename,PATHINFO_FILENAME);        
            $file_name    =    $file_name.".csv";
            $zd         =     gzopen($filename, "r");
            $contents     =     gzread($zd, $fzip_size);
            $file_name    =    "uploads/".$file_name;
            file_put_contents($file_name,addslashes($contents));
            if(file_exists($file_name))
            {
                chmod($file_name,0755);
                unlink($local_file);
            }
            gzclose($zd);
        }
    }
}
ftp_close($conn_id);
?>
utku
пред 18 години
I don't think it would be wise to open a whole gzip file (it _is_ compressed for a reason, and likely to be a very big file) into a single string. You would most likely hit the php memory limits. Instead, if you need to process the file, put your gzread calls in a loop, and read incrementally by a setting $length to a constant value.
imp
пред 2 години
The maximum $length is 2147483647 bytes (2^32-1).

Otherwise gzread() return false.
robinv12001 на yahoo точка co точка in
пред 15 години
Note that this functions' behavior differs from fread in case of EOF.

When you read the last chunk (mean the last bytes from file), it is EOF just after gzread, but in case of fread you need to read once more to get EOF.

Hope, I am clear :)
waldermort на gmail точка com
пред 16 години
<?php
//Extracting the content of a gzip file in php and creating a new csv file using the content
//Create a folder uploads inside current folder
$local_file    =    'test.gz';

//To Get the size of the uncompressed file
$FileRead = $local_file;
$FileOpen = fopen($FileRead, "rb");
fseek($FileOpen, -4, SEEK_END);
$buf = fread($FileOpen, 4);
$GZFileSize = end(unpack("V", $buf));
fclose($FileOpen);
//To Get the size of the zip file

$fzip_size    =    $GZFileSize;
    
$filename    =    $local_file;
$ext        =    pathinfo($filename,PATHINFO_EXTENSION);    
$file_name    =    pathinfo($filename,PATHINFO_FILENAME);        
$file_name    =    $file_name.".csv";

$zd         =     gzopen($filename, "rb");
$contents     =     gzread($zd, $fzip_size);
gzclose($zd);
$file_name    =    "uploads/".$file_name;
$fp    =    fopen($file_name, "wb");
fwrite($fp, $contents); //write contents of feed to cache file
fclose($fp);
if(file_exists($file_name))
{
    chmod($file_name,0755);
    unlink($local_file);
}
?>
denis на bitrix точка ru
19 години пред
As was shown to me in another forum there is a way to get the uncompressed size of the gz file by viewing the last 4 bytes of the gz file.

Here is a piece of code that will do this
<?php
$FileRead = 'SomeText.txt';
$FileOpen = fopen($FileRead, "rb");
        fseek($FileOpen, -4, SEEK_END);
        $buf = fread($FileOpen, 4);
        $GZFileSize = end(unpack("V", $buf));
        fclose($FileOpen);
        $HandleRead = gzopen($FileRead, "rb");
        $ContentRead = gzread($HandleRead, $GZFileSize);
?>

This will read the last 4 bytes of the gz file and use it as the file int for the gzread.

Thanks to stereofrog for helping me with this code.
zaotong на yahoo точка com
пред 15 години
Regarding finding out the lenght of the gz file.
For some reason the seek() function didn't worked, so, I've tried finding out the last 4 bytes using string functions.
That worked pretty well. Here is the code. 
<?php
$stringu='my_beautiful_file.txt.gz';
$gzip=file_get_contents($stringu);
$rest = substr($gzip, -4); 
$GZFileSize = end(unpack("V", $rest));

$FileRead = $stringu;
$HandleRead = gzopen($FileRead, "rb");
$ContentRead = gzread($HandleRead, $GZFileSize);
gzclose($HandleRead);
?>
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.