PHP 8.4.0 RC3 available for testing

fread

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

freadLectura de un fichero en modo binario seguro

Descripción

fread(resource $handle, int $length): string

fread() lee hasta length bytes desde el puntero al fichero referenciado por handle. La lectura termina tan pronto como se encuentre una de las siguientes condiciones:

  • length bytes han sido leídos
  • EOF (fin de fichero) es alcanzado
  • un paquete se encuentra disponible o el tiempo límite del socket se agota (para flujos de red)
  • si el flujo es leído en buffer y no representa un fichero plano, se realiza al menos una lectura de hasta un número de bytes igual al tamaño del trozo (normalmente 8192); dependiendo del la información previamente almacenada en buffer, el tamaño de la información devuelta puede ser mayor que el tamaño del trozo.

Parámetros

handle

Resource que apunta a un fichero del sitema que normalmente es creado usando fopen().

length

Lectura de hasta length número de bytes.

Valores devueltos

Devuelve la cadena leída o false en caso de error.

Ejemplos

Ejemplo #1 Un ejemplo sencillo de fread()

<?php
// poner el contenido de un fichero en una cadena
$nombre_fichero = "/usr/local/algo.txt";
$gestor = fopen($nombre_fichero, "r");
$contenido = fread($gestor, filesize($nombre_fichero));
fclose($gestor);
?>

Ejemplo #2 Ejemplo de lectura binaria de fread()

Advertencia

En sistemas en los que se diferencia entre archivos binarios y de texto (esto es, Windows) el fichero debe ser abierto con 'b' incluida en el parámetro modo de fopen().

<?php
$filename
= "c:\\files\\imagen.gif";
$gestor = fopen($filename, "rb");
$contenido = fread($gestor, filesize($filename));
fclose($gestor);
?>

Ejemplo #3 Ejemplos de lectura remota con fread()

Advertencia

Cuando se lee desde algo que no es un fichero local normal, como los flujos devueltos cuando se leen ficheros remotos o desde popen() y fsockopen(), la lectura se detendrá después de que esté disponible un paquete. Esto significa que debería reuinir la información en trozos como se muestra en los ejemplos de abajo.

<?php
// Para PHP 5 y superior
$gestor = fopen("http://www.example.com/", "rb");
$contenido = stream_get_contents($gestor);
fclose($gestor);
?>
<?php
$gestor
= fopen("http://www.example.com/", "rb");
if (
FALSE === $gestor) {
exit(
"Falló la apertura del flujo a la URL");
}

$contenido = '';
while (!
feof($gestor)) {
$contenido .= fread($gestor, 8192);
}
fclose($gestor);
?>

Notas

Nota:

Si sólo quiere poner el contenido de un fichero en una cadena, use file_get_contents() ya que tiene mucho mejor rendimiento que el código de arriba.

Nota:

Observe que fread() lee desde la posción actual del puntero al fichero. Use ftell() para encontrar la posición actual del puntero y rewind() para rebobinar la posición del puntero.

Ver también

  • fwrite() - Binary-safe file write
  • fopen() - Abre un fichero o un URL
  • fsockopen() - Abre una conexión vía sockets a Internet o a un dominio Unix
  • popen() - Abre un proceso de un puntero a un fichero
  • fgets() - Obtiene una línea desde el puntero a un fichero
  • fgetss() - Obtiene un línea desde un puntero a un archivo y elimina las etiquetas HTML
  • fscanf() - Analiza la entrada desde un archivo de acuerdo a un formato
  • file() - Transfiere un fichero completo a un array
  • fpassthru() - Escribe toda la información restante de un puntero a un archivo
  • ftell() - Devuelve la posición de lectura/escritura actual del puntero a un fichero
  • rewind() - Rebobina la posición de un puntero a un archivo
  • unpack() - Desempaqueta datos de una cadena binaria

add a note

User Contributed Notes 14 notes

up
20
dharmilshah at gmail dot com
10 years ago
For anyone still trying to write an effective file downloader function/script, the work has been done for you in all the major servers including Apache & nginx.

Using the X-Sendfile header, you can do the following:

if ($user->isLoggedIn())
{
header("X-Sendfile: $path_to_somefile_private");
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$somefile\"");
}

Apache will serve the file for you while NOT revealing your private file path! Pretty nice. This works on all browsers/download managers and saves a lot of resources.

Documentation:
Apache module: https://tn123.org/mod_xsendfile/
Nginx: http://wiki.nginx.org/XSendfile
Lighttpd: http://blog.lighttpd.net/articles/2006/07/02/x-sendfile/

Hopefully this will save you many hours of work.
up
25
edgarinvillegas at hotmail dot com
15 years ago
I had a fread script that hanged forever (from php manual):

<?php
$fp
= fsockopen("example.host.com", 80);
if (!
$fp) {
echo
"$errstr ($errno)<br />\n";
} else {
fwrite($fp, "Data sent by socket");
$content = "";
while (!
feof($fp)) { //This looped forever
$content .= fread($fp, 1024);
}
fclose($fp);
echo
$content;
}
?>

The problem is that sometimes end of streaming is not marked by EOF nor a fixed mark, that's why this looped forever. This caused me a lot of headaches...
I solved it using the stream_get_meta_data function and a break statement as the following shows:

<?php
$fp
= fsockopen("example.host.com", 80);
if (!
$fp) {
echo
"$errstr ($errno)<br />\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;
}
?>

Hope this will save a lot of headaches to someone.

(Greetings, from La Paz-Bolivia)
up
11
mail at 3v1n0 dot net
16 years ago
This is an hack I've done to download remote files with HTTP resume support. This is useful if you want to write a download script that fetches files remotely and then sends them to the user, adding support to download managers (I tested it on wget). To do that you should also use a "remote_filesize" function that you can easily write/find.

<?php
function readfile_chunked_remote($filename, $seek = 0, $retbytes = true, $timeout = 3) {
set_time_limit(0);
$defaultchunksize = 1024*1024;
$chunksize = $defaultchunksize;
$buffer = '';
$cnt = 0;
$remotereadfile = false;

if (
preg_match('/[a-zA-Z]+:\/\//', $filename))
$remotereadfile = true;

$handle = @fopen($filename, 'rb');

if (
$handle === false) {
return
false;
}

stream_set_timeout($handle, $timeout);

if (
$seek != 0 && !$remotereadfile)
fseek($handle, $seek);

while (!
feof($handle)) {

if (
$remotereadfile && $seek != 0 && $cnt+$chunksize > $seek)
$chunksize = $seek-$cnt;
else
$chunksize = $defaultchunksize;

$buffer = @fread($handle, $chunksize);

if (
$retbytes || ($remotereadfile && $seek != 0)) {
$cnt += strlen($buffer);
}

if (!
$remotereadfile || ($remotereadfile && $cnt > $seek))
echo
$buffer;

ob_flush();
flush();
}

$info = stream_get_meta_data($handle);

$status = fclose($handle);

if (
$info['timed_out'])
return
false;

if (
$retbytes && $status) {
return
$cnt;
}

return
$status;
}
?>
up
24
Edward Jaramilla
16 years ago
I couldn't get some of the previous resume scripts to work with Free Download Manager or Firefox. I did some clean up and modified the code a little.

Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)

<?php

function dl_file_resumable($file, $is_resume=TRUE)
{
//First, see if the file exists
if (!is_file($file))
{
die(
"<b>404 File not found!</b>");
}

//Gather relevent info about file
$size = filesize($file);
$fileinfo = pathinfo($file);

//workaround for IE filename bug with multiple periods / multiple dots in filename
//that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
$filename = (strstr($_SERVER['HTTP_USER_AGENT'], 'MSIE')) ?
preg_replace('/\./', '%2e', $fileinfo['basename'], substr_count($fileinfo['basename'], '.') - 1) :
$fileinfo['basename'];

$file_extension = strtolower($path_info['extension']);

//This will set the Content-Type to the appropriate setting for the file
switch($file_extension)
{
case
'exe': $ctype='application/octet-stream'; break;
case
'zip': $ctype='application/zip'; break;
case
'mp3': $ctype='audio/mpeg'; break;
case
'mpg': $ctype='video/mpeg'; break;
case
'avi': $ctype='video/x-msvideo'; break;
default:
$ctype='application/force-download';
}

//check if http_range is sent by browser (or download manager)
if($is_resume && isset($_SERVER['HTTP_RANGE']))
{
list(
$size_unit, $range_orig) = explode('=', $_SERVER['HTTP_RANGE'], 2);

if (
$size_unit == 'bytes')
{
//multiple ranges could be specified at the same time, but for simplicity only serve the first range
//http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
list($range, $extra_ranges) = explode(',', $range_orig, 2);
}
else
{
$range = '';
}
}
else
{
$range = '';
}

//figure out download piece from range (if set)
list($seek_start, $seek_end) = explode('-', $range, 2);

//set start and end based on range (if set), else set defaults
//also check for invalid ranges.
$seek_end = (empty($seek_end)) ? ($size - 1) : min(abs(intval($seek_end)),($size - 1));
$seek_start = (empty($seek_start) || $seek_end < abs(intval($seek_start))) ? 0 : max(abs(intval($seek_start)),0);

//add headers if resumable
if ($is_resume)
{
//Only send partial content header if downloading a piece of the file (IE workaround)
if ($seek_start > 0 || $seek_end < ($size - 1))
{
header('HTTP/1.1 206 Partial Content');
}

header('Accept-Ranges: bytes');
header('Content-Range: bytes '.$seek_start.'-'.$seek_end.'/'.$size);
}

//headers for IE Bugs (is this necessary?)
//header("Cache-Control: cache, must-revalidate");
//header("Pragma: public");

header('Content-Type: ' . $ctype);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: '.($seek_end - $seek_start + 1));

//open the file
$fp = fopen($file, 'rb');
//seek to start of missing part
fseek($fp, $seek_start);

//start buffered download
while(!feof($fp))
{
//reset time limit for big files
set_time_limit(0);
print(
fread($fp, 1024*8));
flush();
ob_flush();
}

fclose($fp);
exit;
}

?>
up
7
john dot wellesz at teaser dot com
10 years ago
Note that fread() will return '' (empty string) when a timeout occurs unlike socket_read() which returns false...
up
9
matt at matt-darby dot com
17 years ago
I thought I had an issue where fread() would fail on files > 30M in size. I tried a file_get_contents() method with the same results. The issue was not reading the file, but echoing its data back to the browser.

Basically, you need to split up the filedata into manageable chunks before firing it off to the browser:

<?php

$total
= filesize($filepath);
$blocksize = (2 << 20); //2M chunks
$sent = 0;
$handle = fopen($filepath, "r");

// Push headers that tell what kind of file is coming down the pike
header('Content-type: '.$content_type);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-length: '.$filesize * 1024);

// Now we need to loop through the file and echo out chunks of file data
// Dumping the whole file fails at > 30M!
while($sent < $total){
echo
fread($handle, $blocksize);
$sent += $blocksize;
}

exit(
0);

?>

Hope this helps someone!
up
8
randym
13 years ago
Concerning [problems with UTF-8 and] downloading Zip files I found that simply adding 3 lines of code before starting the fread to the buffer for delivery in all browsers solved the problem.

<?php
ob_end_clean
();
ob_start();
header( 'Content-Type:' );
?>

... see where placed in the function below:

<?php
function readfile_chunked( $filename, $retbytes = true ) {
$chunksize = 1 * (1024 * 1024); // how many bytes per chunk
$buffer = '';
$cnt = 0;
$handle = fopen( $filename, 'rb' );
if (
$handle === false ) {
return
false;
}
ob_end_clean(); //added to fix ZIP file corruption
ob_start(); //added to fix ZIP file corruption
header( 'Content-Type:' ); //added to fix ZIP file corruption
while ( !feof( $handle ) ) {
$buffer = fread( $handle, $chunksize );
//$buffer = str_replace("","",$buffer);
echo $buffer;
ob_flush();
flush();
if (
$retbytes ) {
$cnt += strlen( $buffer );
}
}
$status = fclose( $handle );
if (
$retbytes && $status ) {
return
$cnt; // return num. bytes delivered like readfile() does.
}
return
$status;
}
?>
up
7
Anonymous
16 years ago
It might be worth noting that if your site uses a front controller with sessions and you send a large file to a user; you should end the session just before sending the file, otherwise the user will not be able to continue continue browsing the site while the file is downloading.
up
3
shocker at shockingsoft dot com
16 years ago
If you read from a socket connection or any other stream that may delay when responsing but you want to set a timeout you can use stream_set_timeout():

<?php
$f
= fsockopen("127.0.0.1", 123);
if (
$f)
{
fwrite($f, "hello");
stream_set_timeout($f, 5); //5 seconds read timeout
if (!fread($f, 5)) echo "Error while reading";
else echo
"Read ok";
fclose($f);
}
?>
up
4
Anonymous
13 years ago
If you serve a file download over PHP with fread and print/echo and experience corrupted binary files, chances are the server still uses magic quotes and escapes the null bytes in your file. Although from 5.3.0 magic quotes are no longer supported, you might still encounter this problem. Try to turn them off by placing this code before using fread:

<?php
@ini_set('magic_quotes_runtime', 0);
?>
up
2
mrhappy[at]dotgeek.org
19 years ago
Just a note for anybody trying to implement a php handled download script -

We spent a long time trying to figure out why our code was eating system resources on large files.. Eventually we managed to trace it to output buffering that was being started on every page via an include.. (It was attempting to buffer the entire 600 Megs or whatever size *before* sending data to the client) if you have this problem you may want to check that first and either not start buffering or close that in the usual way :)

Hope that prevents somebody spending hours trying to fix an obscure issue.

Regards :)
up
1
Richard Dale richard at premiumdata dot n dot e dot t
19 years ago
If you use any of the above code for downloadinng files, Internet Explorer will change the filename if it has multiple periods in it to something with square brackets. To work around this, we check to see if the User Agent contains MSIE and rewrite the necessary periods as %2E

<?php
# eg. $filename="setup.abc.exe";
if (strstr($_SERVER['HTTP_USER_AGENT'], "MSIE")) {
# workaround for IE filename bug with multiple periods / multiple dots in filename
# that adds square brackets to filename - eg. setup.abc.exe becomes setup[1].abc.exe
$iefilename = preg_replace('/\./', '%2e', $filename, substr_count($filename, '.') - 1);
header("Content-Disposition: attachment; filename=$iefilename" );
} else {
header("Content-Disposition: attachment; filename=$filename");
}
?>
up
3
m (at) mindplay (dot) dk
19 years ago
Here's a function for sending a file to the client - it may look more complicated than necessary, but has a number of advantages over simpler file sending functions:

- Works with large files, and uses only an 8KB buffer per transfer.

- Stops transferring if the client is disconnected (unlike many scripts, that continue to read and buffer the entire file, wasting valuable resources) but does not halt the script

- Returns TRUE if transfer was completed, or FALSE if the client was disconnected before completing the download - you'll often need this, so you can log downloads correctly.

- Sends a number of headers, including ones that ensure it's cached for a maximum of 2 hours on any browser/proxy, and "Content-Length" which most people seem to forget.

(tested on Linux (Apache) and Windows (IIS5/6) under PHP4.3.x)

Note that the folder from which protected files will be pulled, is set as a constant in this function (/protected) ... Now here's the function:

<?php
function send_file($name) {
ob_end_clean();
$path = "protected/".$name;
if (!
is_file($path) or connection_status()!=0) return(FALSE);
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
header("Content-Type: application/octet-stream");
header("Content-Length: ".(string)(filesize($path)));
header("Content-Disposition: inline; filename=$name");
header("Content-Transfer-Encoding: binary\n");
if (
$file = fopen($path, 'rb')) {
while(!
feof($file) and (connection_status()==0)) {
print(
fread($file, 1024*8));
flush();
}
fclose($file);
}
return((
connection_status()==0) and !connection_aborted());
}
?>

And here's an example of using the function:

<?php
if (!send_file("platinumdemo.zip")) {
die (
"file transfer failed");
// either the file transfer was incomplete
// or the file was not found
} else {
// the download was a success
// log, or do whatever else
}
?>

Regards,
Rasmus Schultz
up
0
admin at codebydeer dot com
1 month ago
You need to know that if the $length parameter of fread() is 0, it will be Faltal Error.
<?php
$filepath
= "example/a/dir/file.txt";

$fp = fopen($filepath, "c+");
fseek($fp, 0);
$fileSize = fstat($fp)["size"];
if (
$fileSize <= 0) {
$txt = "";
} else {
$txt = fread($fp, $fileSize);
}
echo
$txt;
?>
I'm Japanese so if I took some mistakes, very sorry.
thanks!
To Top