Php fread all contents

fread

Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .

length указывает размер прочитанных данных в байтах.

Возвращаемые значения

Возвращает прочтённую строку или false в случае возникновения ошибки.

Примеры

Пример #1 Простой пример использования fread()

// получает содержимое файла в строку
$filename = «/usr/local/something.txt» ;
$handle = fopen ( $filename , «r» );
$contents = fread ( $handle , filesize ( $filename ));
fclose ( $handle );
?>

Пример #2 Пример бинарного чтения с помощью fread()

На системах, которые различают бинарные и текстовые файлы (к примеру, Windows), файл должен быть открыт с использованием флага ‘b’ в параметре mode функции fopen() .

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

Пример #3 Примеры удалённого чтения с помощью fread()

При чтении чего-либо отличного от локальных файлов, например потоков, возвращаемых при чтении удалённых файлов или из popen() и fsockopen() , чтение остановится после того, как пакет станет доступным. Это означает, что вы должны собирать данные вместе по кусочкам, как показано на примере ниже.

$handle = fopen ( «http://www.example.com/» , «rb» );
$contents = stream_get_contents ( $handle );
fclose ( $handle );
?>

$handle = fopen ( «http://www.example.com/» , «rb» );
if ( FALSE === $handle ) exit( «Не удалось открыть поток по url адресу» );
>

while (! feof ( $handle )) $contents .= fread ( $handle , 8192 );
>
fclose ( $handle );
?>

Примечания

Замечание:

Если вы просто хотите получить содержимое файла в виде строки, используйте file_get_contents() , так как эта функция намного производительнее, чем код описанный выше.

Замечание:

Учтите, что fread() читает, начиная с текущей позиции файлового указателя. Используйте функцию ftell() для нахождения текущей позиции указателя и функцию rewind() для перемотки позиции указателя в начало.

Смотрите также

  • fwrite() — Бинарно-безопасная запись в файл
  • fopen() — Открывает файл или URL
  • fsockopen() — Открывает соединение с интернет-сокетом или доменным сокетом Unix
  • popen() — Открывает файловый указатель процесса
  • fgets() — Читает строку из файла
  • fgetss() — Читает строку из файла и удаляет HTML-теги
  • fscanf() — Обрабатывает данные из файла в соответствии с форматом
  • file() — Читает содержимое файла и помещает его в массив
  • fpassthru() — Выводит все оставшиеся данные из файлового указателя
  • fseek() — Устанавливает смещение в файловом указателе
  • ftell() — Возвращает текущую позицию указателя чтения/записи файла
  • rewind() — Сбрасывает курсор файлового указателя
  • unpack() — Распаковать данные из бинарной строки
Читайте также:  Пояснение работы парсера

User Contributed Notes 32 notes

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)

function dl_file_resumable ( $file , $is_resume = TRUE )
//First, see if the file exists
if (! is_file ( $file ))
die( «404 File not found!» );
>

//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’ ;
>

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 keyword»>. $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 );

Читайте также:  Table column header css

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

Источник

PHP Read File

Summary: in this tutorial, you’ll learn how to read a file using the various built-in PHP functions.

To read the contents from a file, you follow these steps:

  • Open the file for reading using the fopen() function.
  • Read the contents from the file using the fread() function.
  • Close the file using the fclose() function.

Here’s the syntax of the fread() function:

fread ( resource $stream , int $length ) : string|falseCode language: PHP (php)

The fread() function has two parameters:

  • The $stream is a file system pointer resource, which is typically the result of the fopen() function.
  • The $length specifies the maximum number of bytes to read. If you want to read the entire file, you can pass the file size to the $length parameter.

The fread() function returns the file contents or false if it fails to read.

The fread() function stops reading the file once the $length number of bytes has been read or the end of file (EOF) has been reached.

To check if the file pointer is at end of file, you can pass it to the feof() function:

feof ( resource $stream ) : bool Code language: PHP (php)

The feof() function returns true if the $stream is at the EOF or an error occurs. Otherwise, it returns false .

To read a file line by line, you use the fgets() function:

fgets ( resource $handle , int $length = ? ) : string|falseCode language: PHP (php)

Like the fread() function, the fgets() function accepts a file system pointer resource and up to a number of bytes to read. If you omit the $length argument, the fread() function will read the entire line.

PHP read file examples

Let’s take some examples of how to read a file.

1) Read the entire file into a string

Suppose that you have a file named population.txt located at public directory with the following contents:

1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,643 4 Houston Texas 2,316,120 5 Phoenix Arizona 1,708,127 6 Philadelphia Pennsylvania 1,578,487 7 San Antonio Texas 1,567,118 8 San Diego California 1,422,420 9 Dallas Texas 1,343,266 10 San Jose California 1,013,616 Code language: plaintext (plaintext)

The following example uses the fread() function to read the contents of the entire population.txt file into a string and shows it on the webpage:

 $filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, filesize($filename)); fclose($f); echo nl2br($contents); > Code language: HTML, XML (xml)

First, open the population.txt file using the fopen() function:

$f = fopen($filename, 'r');Code language: PHP (php)

Second, read the contents of the entire file using the fread() function; use the filesize() function to get the size of the file:

$contents = fread($f, filesize($filename));Code language: PHP (php)

Third, show the contents of the file on a web page; use the nl2br() function to convert the newline characters to
tags.

echo nl2br($contents);Code language: PHP (php)

Finally, close the file using the fclose() function.

Note that the file_get_contents() function is a shortcut for opening a file, reading the whole file’s contents into a string, and close it.

2) Read some characters from a file

To read some characters from a file, you specify the number of bytes to read. The following example uses the fread() function to read up to 100 bytes from the population.txt file:

 $filename = './public/population.txt'; $f = fopen($filename, 'r'); if ($f) < $contents = fread($f, 100); fclose($f); echo nl2br($contents); >Code language: HTML, XML (xml)
1 New York New York 8,253,213 2 Los Angeles California 3,970,219 3 Chicago Illinois 2,677,64Code language: plaintext (plaintext)

3) Read a file line by line

The following example uses the fgets() funtion to read the population.txt file line by line:

 $filename = './public/population.txt'; $lines = []; $f = fopen($filename, 'r'); if (!$f) < return; > while (!feof($f)) < $lines[] = fgets($f); >print_r($lines); fclose($f);Code language: HTML, XML (xml)

Summary

  • Use the fread() function to read some or all contents from a file.
  • Use the fgets() function to read a line from a file.
  • Use the feof() function to test the end-of-file has been reached.
  • Use the filesize() function to get the size of the file.

Источник

PHP fread() Function

The function will stop at the end of the file or when it reaches the specified length, whichever comes first.

Syntax

Parameter Values

Parameter Description
file Required. Specifies the open file to read from
length Required. Specifies the maximum number of bytes to read

Technical Details

More Examples

Example

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью