Php fread function and fread function usage

Source: Internet
Author: User
Tags fread

Fread syntax:
String fread (resource $ handle, int $ length)

The length of the byte read by fread () is determined by the pointer to the file being referenced. Read as soon as possible to meet one of the following conditions:

Length of read bytes
! Eof (end of file) reaches
One package available network (stream)
8192 bytes read (User space stream opened)

*/

// Fread reads file instance 1

The code is as follows: Copy code
$ Filename = "/www.111cn.net/local/something.txt ";
$ Handle = fopen ($ filename, "r ");
$ Contents = fread ($ handle, filesize ($ filename ));
Fclose ($ handle );

// Php5 and later versions read remote server content

The code is as follows: Copy code
$ Handle = fopen ("http://www.111cn.net/", "rb ");
$ Contents = stream_get_contents ($ handle );
Fclose ($ handle );


//

The code is as follows: Copy code
$ Handle = fopen ("http://down.111cn.net/", "rb ");
$ Contents = '';
While (! Feof ($ handle )){
$ Contents. = fread ($ handle, 8192 );
}
Fclose ($ handle );

/*
Sometimes the purpose of a stream is not to use the eof mark, nor is it a fixed sign, which is why this loop is always used. This caused me a lot of troubles...
I solve this problem by using the stream_get_meta_data function. The following shows a break statement:

*/

The code is as follows: Copy code
$ Fp = fsockopen ("mb.111cn.net", 80 );
If (! $ Fp ){
Echo "$ errstr ($ errno) <br/> ";
} 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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.