- PHP Read File
- PHP read file examples
- 1) Read the entire file into a string
- 2) Read some characters from a file
- 3) Read a file line by line
- Summary
- PHP | Открытие, чтение, закрытие файлов
- Функция PHP fopen()
- Синтаксис
- Параметры
- Пример
- Чтение файла — fread()
- Закрытие файла — fclose()
- Синтаксис
- Однострочное чтение — fgets()
- Пример
- Проверка окончания файла — feof()
- Пример
- Чтение одного символа — fgetc()
- Пример
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|false
Code 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|false
Code 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,64
Code 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 | Открытие, чтение, закрытие файлов
В этой уроке мы рассмотрим несколько функций, с помощью которых будем открывать, читать и закрывать файлы на сервере.
Функция PHP fopen()
Функция fopen() в PHP — это встроенная функция, которая используется для открытия файла или URL-адреса. В случае сбоя, она возвращает FALSE и выдаёт ошибку. Если вам нужно скрыть вывод ошибки добавьте символ ‘@’ перед именем функции.
Синтаксис
Параметры
- filename : Обязательный параметр, определяющий файл.
- mode : Обязательный параметр, определяющий тип доступа к файлу или потоку.
Он может иметь следующие возможные значения:- «r»: Открывает файл только для чтения; помещает указатель в начало файла.
- «r+»: Окрывает файл для чтения и записи; помещяет указатель в начало файла.
- «w»: Открывает файл только для записи; помещает указатель в начало файла и обрезает файл до нулевой длинны. Если файл не существует — пробует его создать.
- «w+»: Открывает файл для чтения и записи; помещает указатель в начало файла и обрезает файл до нулевой длинны. Если файл не существует — пробует его создать.
- «a»: Открывает файл только для записи; помещает указатель в конец файла. Если файл не существует — пытается его создать.
- «a+»: Открывает файл для чтения и записи; помещает указатель в конец файла. Если файл не существует — пытается его создать.
- «x»: Создаёт и открывает только для записи. Он создает новый файл и возвращает FALSE и ошибку, если файл уже существует.
- «x+»: Создаёт и открывает для чтения и записи. Создает новый файл и возвращает FALSE и ошибку, если файл уже существует.
- «c»: Открывает файл только для записи. Если файл не существует, то он создается. Если же файл существует, то он не обрезается (в отличие от ‘w’), и вызов к этой функции не вызывает ошибку (также как и в случае с ‘x’).
- «c+»: Открывает файл для чтения и записи; в остальном имеет то же поведение, что и ‘c’.
- «e»: Установить флаг close-on-exec (закрыть при запуске) на открытый файловый дескриптор. Доступно только в PHP скомпилированном на системах поддерживающих POSIX.1-2008.
В этом уроке мы будем использовать текстовый файл mane.txt:
AJAX = Asynchronous JavaScript and XML CSS = Cascading Style Sheets HTML = Hyper Text Markup Language PHP = PHP Hypertext Preprocessor SQL = Structured Query Language SVG = Scalable Vector Graphics XML = EXtensible Markup Language
В следующем примере, ипользуя функцию fopen() , откроем файл «mane.txt» в режиме чтения:
Пример
echo fread($myfile,filesize("mane.txt"));
fclose($myfile);
?>Конструкция or die(«Невозможно открыть файл!») позволяет прекратить работу скрипта и вывесте некоторое сообщение об ошибке, если функция fopen не смогла открыть файл.
Чтение файла — fread()
Функция fread() считывает информацию из открытого файла.
Первый параметр fread() содержит имя файла для чтения, а второй параметр указывает максимальное количество байтов для чтения.
Следующий код PHP читает файл «mane.txt» до конца:
Закрытие файла — fclose()
Функция fclose() используется, чтобы закрыть открытый файл.
Синтаксис
bool fclose ( resource handle )
Функция закрывает файл, на который указывает handle.
Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.
Дескриптор должен указывать на файл, открытый ранее с помощью функции fopen() или fsockopen() .
Примечание: Хорошая практика программирования — закрывать все файлы после того, как вы закончили с ними работать. Дело в том, что открытый файл на вашем сервере продолжает занимать ресурсы!
Однострочное чтение — fgets()
Функция fgets() используется для чтения одной строки из файла.
В приведенном ниже примере выводится первая строка файла mane.txt:
Пример
echo fgets($myfile);
fclose($myfile);
?>Примечание: После вызова функции fgets() указатель файла переместился на следующую строку.
Проверка окончания файла — feof()
Функция feof() определяет, достигнут ли конец файла. Если в указанном дескрипторе, определяется окончание файла, возвращает True . В противном случае, False .
Функция feof() полезна для цикла работающего с данным неизвестной длины.
В приведенном ниже примере файл «mane.txt» считывается построчно, пока не будет достигнут конец файла:
Пример
while(!feof($myfile)) < // цикл завершится, при обнаружении конца файла
echo fgets($myfile) . "
"; // Вывести одну строку
>
?>Чтение одного символа — fgetc()
Функция fgetc() используется для чтения одного символа из файла.
В приведенном ниже примере файл «mane.txt» считывается посимвольно, пока не будет достигнут конец файла:
Пример
while(!feof($myfile)) < // цикл завершится, при обнаружении конца файла
echo fgetc($myfile) . "
"; // Вывести один символ
>
?>Примечание: Не перепутайте имя функции fgets() оканчивается символом s — string, а имя функции fgetc() оканчивается символом c — character.