- fread
- Возвращаемые значения
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 32 notes
- File Handling in PHP
- Introduction
- PHP fopen() Function
- Explanation
- PHP fclose() Function
- PHP fread() Function
- Parameters:
- Return Value:
- Example:
- PHP fwrite() Function
- Explanation
- PHP Delete File — unlink()
- Explanation
- Conclusion
fread
Указатель ( resource ) на файл, обычно создаваемый с помощью функции fopen() .
length указывает размер прочитанных данных в байтах.
Возвращаемые значения
Возвращает прочтённую строку или false в случае возникновения ошибки.
Примеры
Пример #1 Простой пример использования fread()
// получает содержимое файла в строку
$filename = «/usr/local/something.txt» ;
$handle = fopen ( $filename , «r» );
$contents = fread ( $handle , filesize ( $filename ));
fclose ( $handle );
?>?php
Пример #2 Пример бинарного чтения с помощью fread()
На системах, которые различают бинарные и текстовые файлы (к примеру, Windows), файл должен быть открыт с использованием флага ‘b’ в параметре mode функции fopen() .
$filename = «c:\\files\\somepic.gif» ;
$handle = fopen ( $filename , «rb» );
$contents = fread ( $handle , filesize ( $filename ));
fclose ( $handle );
?>?php
Пример #3 Примеры удалённого чтения с помощью fread()
При чтении чего-либо отличного от локальных файлов, например потоков, возвращаемых при чтении удалённых файлов или из popen() и fsockopen() , чтение остановится после того, как пакет станет доступным. Это означает, что вы должны собирать данные вместе по кусочкам, как показано на примере ниже.
$handle = fopen ( «http://www.example.com/» , «rb» );
$contents = stream_get_contents ( $handle );
fclose ( $handle );
?>?php
$handle = fopen ( «http://www.example.com/» , «rb» );
if ( FALSE === $handle ) exit( «Не удалось открыть поток по url адресу» );
>
?php
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 );
//start buffered download
while(! feof ( $fp ))
//reset time limit for big files
set_time_limit ( 0 );
print( fread ( $fp , 1024 * 8 ));
flush ();
ob_flush ();
>
File Handling in PHP
File handling in PHP refers to the various functions and methods available in the language that enable developers to read, write, manipulate, and manage files and directories on a server or local machine. PHP provides several built-in functions like open (), fwrite(), fread() , fclose() , and others to manipulate files in different modes like read, write, append, binary, etc. PHP also provides functions to manage directories, such as opendir() to open a directory, readdir() to read the contents of a directory and closedir() to close a directory. These functions enable developers to create, move, rename, delete, and manage files and directories.
Introduction
File handling is a crucial aspect of programming that involves creating, reading, writing, and deleting files. In PHP, file handling plays a vital role in web development, especially when dealing with tasks such as data storage, retrieval, and manipulation. Understanding file handling in PHP requires knowledge of the functions and techniques available to effectively perform these tasks.
PHP provides a rich set of built-in functions for file handling, which can be used to perform a variety of operations on files, including opening, reading, writing, and closing files. With a good understanding of file handling in PHP, developers can create powerful web applications that can handle various file-related tasks efficiently.
PHP fopen() Function
The fopen() function in PHP is used to open a file or URL and returns a file pointer resource that can be used to read, write, or manipulate the file.
The syntax of fopen() is as follows:
- $filename is the name of the file or URL to open
- $mode is the mode in which to open the file. This can be one of the following:
- ‘r’ : read only
- ‘w’ : write only (truncates the file to zero length or creates a new file)
- ‘a’ : append-only (opens the file for writing at the end of the file)
- ‘x’ : exclusive write (creates a new file and opens it for writing only if it doesn’t already exist)
- ‘b’ : binary mode (used in conjunction with the above modes to indicate that the file should be opened in binary mode)
- ‘t’ : text mode (used in conjunction with the above modes to indicate that the file should be opened in text mode)
- $use_include_path is a boolean parameter that indicates whether to search for the file in the include path (if set)
- $context is an optional parameter that allows you to specify a context for the file stream (e.g. HTTP headers, SSL settings, etc.)
Here’s an example that demonstrates how to use fopen() to open a file in read-only mode, read its contents line by line, and then close the file:
Explanation
In this example, the file example.txt is opened in read-only mode using fopen(). The while loop reads the file line by line using the fgets() function, and the contents of each line are echoed to the screen. Finally, the fclose() function is called to close the file.
PHP fclose() Function
The PHP fclose() function is used to close an open file pointer or handle in PHP. It is typically used after a file has been opened using fopen() or a related function.
Here is the syntax for the fclose() function:
The function takes a single parameter, which is the file pointer or handles to be closed. The function returns a boolean value indicating whether the file was successfully closed or not.
Here’s an example that demonstrates how to use fclose() in PHP:
PHP fread() Function
The PHP fread() function is used to read a specified number of bytes from a file. It is a file-handling function in PHP that allows you to read data from a file. Syntax:
Parameters:
$file_handle : Required. Specifies the file pointer or file handle to read from. $length : Required. Specifies the number of bytes to read from the file.
Return Value:
Returns the read data as a string.
Example:
Suppose we have a file example.txt with the following content:
And we want to read the first 10 bytes of this file using the fread() function. Here’s how we can do that:
PHP fwrite() Function
The PHP fwrite() function is used to write data to a file. It takes three parameters: a file pointer, a string to be written, and an optional parameter that specifies the maximum number of bytes to write.
Here’s the syntax of the fwrite() function:
- resource $handle: A file pointer, which is a reference to the opened file. It can be obtained using functions such as fopen() , fsockopen() , and tmpfile() .
- string $string: The string to be written to the file.
- int $length: An optional parameter that specifies the maximum number of bytes to be written. If this parameter is not specified, all the data in the string will be written to the file.
- The fwrite() function returns the number of bytes written to the file, or false on error.
Here’s an example of how to use the fwrite() function to write data to a file:
Explanation
In this example, we first open a file named «data.txt» in write mode using the fopen() function. We then check if the file was successfully opened, and if it was, we write the string «Hello, World!\n» to the file using the fwrite() function.
PHP Delete File — unlink()
In PHP, the unlink() function is used to delete a file from the file system. It accepts a single argument, which is the path to the file that needs to be deleted.
Here is the syntax of the unlink() function:
Here is an example of using the unlink() function to delete a file:
Explanation
In this example, we first check if the file exists using the file_exists() function. If the file exists, we attempt to delete it using the unlink() function. If the unlink() function returns true, we display a success message. If it returns false, we display an error message.
It is important to note that the unlink() function permanently deletes the file, so be careful when using it. Once a file is deleted using unlink(), it cannot be recovered.
Conclusion
- File handling in PHP involves opening, reading, writing, and manipulating files stored on a file system.
- The fopen() function is used to open a file for reading, writing, or appending.
- The fwrite() function is used to write to a file, while the fread() function is used to read from a file.
- The fgets() function can be used to read a single line from a file.
- The fclose() function should be used to close a file after reading or writing to it.