downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  

<fputsfscanf>
Last updated: Thu, 26 Jun 2008

fread

(PHP 4, PHP 5)

fread — Binary-safe file read

Description

string fread ( resource $handle , int $length )

fread() reads up to length bytes from the file pointer referenced by handle . Reading stops as soon as one of the following conditions is met:

  • length bytes have been read
  • EOF (end of file) is reached
  • a packet becomes available (for network streams)
  • 8192 bytes have been read (after opening userspace stream)

Parameters

handle

A file system pointer resource that is typically created using fopen().

length

Up to length number of bytes read.

Return Values

Returns the read string or FALSE in case of error.

Examples

Example #1 A simple fread() example

<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #2 Binary fread() example

Warning

On systems which differentiate between binary and text files (i.e. Windows) the file must be opened with 'b' included in fopen() mode parameter.

<?php
$filename
= "c:\files\somepic.gif";
$handle = fopen($filename, "rb");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>

Example #3 Remote fread() examples

Warning

When reading from anything that is not a regular local file, such as streams returned when reading remote files or from popen() and fsockopen(), reading will stop after a packet is available. This means that you should collect the data together in chunks as shown in the examples below.

<?php
// For PHP 5 and up
$handle = fopen("http://www.example.com/", "rb");
$contents = stream_get_contents($handle);
fclose($handle);
?>
<?php
$handle
= fopen("http://www.example.com/", "rb");
$contents = '';
while (!
feof($handle)) {
 
$contents .= fread($handle, 8192);
}
fclose($handle);
?>

Notes

Note: If you just want to get the contents of a file into a string, use file_get_contents() as it has much better performance than the code above.



add a noteadd a note User Contributed Notes
Binary-safe file read
There are no user contributed notes for this page.




<fputsfscanf>
Last updated: Thu, 26 Jun 2008
show source | credits | sitemap | contact | advertising | mirror sites
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: http://phpbuilder.com/
Last updated: Tue Nov 1 20:20:59 2005 EST
Columns / Articles | Tips / Quickies | News | News Linking and RSS Feeds | Shared Code Library
Mail Archives | Support / Discussion Forums | Get Started! Links | Contribute! | Docs