Home  >  Article  >  Backend Development  >  PHP fread function and fread function usage_PHP tutorial

PHP fread function and fread function usage_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 11:01:161230browse

PHP fread function and fread function usage ​

php tutorial fread function and fread function usage
/*
fread syntax:
string fread ( resource $handle , int $length )

The byte length read by fread() is processed by the file pointer referenced. Read as soon as possible on pairs that meet one of the following conditions:

Length of bytes read
!eof (end of file) reached
A package of available networks (streams)
8192 bytes read (userspace stream after opening)

*/

//fread file reading example 1

$filename = "/www.bkjia.com/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);

//php5 and above versions read the content of the remote server

$handle = fopen("http://www.bkjia.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);


//

$handle = fopen("http://down.php100.com/", "rb");
$contents = '';
while (!feof($handle)) {
$contents .= fread($handle, 8192);
}
fclose($handle);

/*
Sometimes the purpose of the stream is not marked with eof nor a fixed flag, that's why this loop takes forever. This caused me a lot of trouble...
I solved it using stream_get_meta_data function with a break statement as shown below:

*/

$fp = fsockopen("mb.php100.com", 80);
if (!$fp) {
echo "$errstr ($errno)
n";
} else {
​​ fwrite($fp, "data sent by socket");
$content = "";
While (!feof($fp)) {
$content .= fread($fp, 1024);
          $stream_meta_data = stream_get_meta_data($fp); //added line
If($stream_meta_data['unread_bytes'] <= 0) break; //added line
}
fclose($fp);
echo $content;
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445443.htmlTechArticlephp fread function and fread function usage php tutorial fread function and fread function usage/* fread syntax: string fread ( resource $handle, int $length) The length of bytes read by fread() is determined by the processing...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn