PHP File Open/Read

6 min read

In this chapter we will teach you how to open, read, and close a file on the server.

Энэ бүлэгт бид сервер дээр файл нээх, унших, хаах талаар заах болно.


PHP Open File – fopen() #

A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.

Файлуудыг нээх илүү сайн арга бол fopen() функц юм. Энэ функц нь readfile()функцээс илүү олон сонголтыг өгдөг.

We will use the text file, “webdictionary.txt”, during the lessons:

Хичээлийн явцад бид “webdictionary.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

The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:

Fopen () эхний параметр нь нээгдэх файлын нэрийг агуулдаг бөгөөд хоёр дахь параметр нь файлыг ямар горимд нээхийг зааж өгдөг. Дараах жишээ нь fopen () функц нь заасан файлыг нээх боломжгүй бол мессеж үүсгэдэг:

Example #

Жишээ #

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fread($myfile,filesize("webdictionary.txt")); fclose($myfile); ?>

Tip: The fread() and the fclose() functions will be explained below.

Зөвлөгөө: fread() ба fclose() функцуудыг доор тайлбарлах болно.

The file may be opened in one of the following modes:

Файлыг дараахь горимуудын аль нэгээр нээж болно:

Modes Description
r Open a file for read only. File pointer starts at the beginning of the file

Зөвхөн унших зориулалттай файл нээнэ үү. Файл заагч нь файлын эхнээс эхэлдэг

w

Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file

Зөвхөн бичихийн тулд файл нээнэ үү. Файлын агуулгыг устгах эсвэл хэрэв байхгүй бол шинэ файл үүсгэх. Файл заагч нь файлын эхнээс эхэлдэг

a Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist

Зөвхөн бичихийн тулд файл нээнэ үү. Файл дахь одоо байгаа өгөгдлийг хадгалсан болно. Файлын заагч нь файлын төгсгөлд эхэлдэг. Хэрэв файл байхгүй бол шинэ файл үүсгэдэг

x

Creates a new file for write only. Returns FALSE and an error if file already exists

Зөвхөн бичихэд зориулж шинэ файл үүсгэдэг. FALSE-г буцаана, хэрэв файл байгаа бол алдаа гаргана

r+

Open a file for read/write. File pointer starts at the beginning of the file

Унших / бичих файлыг нээнэ үү. Файл заагч нь файлын эхнээс эхэлдэг

w+

Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file

Унших / бичих файлыг нээнэ үү. Файлын агуулгыг устгах эсвэл хэрэв байхгүй бол шинэ файл үүсгэх. Файл заагч нь файлын эхнээс эхэлдэг

a+

Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist

Унших / бичих файлыг нээнэ үү. Файл дахь одоо байгаа өгөгдлийг хадгалсан болно. Файлын заагч нь файлын төгсгөлд эхэлдэг. Хэрэв файл байхгүй бол шинэ файл үүсгэдэг

x+

Creates a new file for read/write. Returns FALSE and an error if file already exists

Унших / бичих шинэ файл үүсгэдэг. FALSE-г буцаана, хэрэв файл байгаа бол алдаа гаргана


 
 
 
 
 
 
 

PHP Read File – fread() #

The fread() function reads from an open file.

fread() функц нь нээлттэй файлаас уншдаг.

The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.

fread() -ийн эхний параметр нь унших файлын нэрийг агуулдаг бөгөөд хоёр дахь параметр нь хамгийн их байтыг уншиж өгөхийг зааж өгдөг.

The following PHP code reads the “webdictionary.txt” file to the end:

Дараахь PHP код нь “webdictionary.txt” файлыг эцэс хүртэл уншина.

fread($myfile,filesize(“webdictionary.txt”));

PHP Close File – fclose() #

The fclose() function is used to close an open file.

fclose()функцийг нээлттэй файлыг хаахад ашигладаг.

It’s a good programming practice to close all files after you have finished with them. You don’t want an open file running around on your server taking up resources!

Бүх файлуудыг дуусгасны дараа хаах нь програмчлалын сайн практик юм. Та нээлттэй файлыг сервер дээрээ ажиллуулахыг хүсэхгүй байна!

The fclose() requires the name of the file (or a variable that holds the filename) we want to close:

Fclose () нь бидний хаахыг хүсч буй файлын нэрийг (эсвэл файлын нэрийг агуулдаг хувьсагч) шаарддаг:

<?php $myfile = fopen("webdictionary.txt", "r"); // some code to be executed.... fclose($myfile); ?>

PHP Read Single Line – fgets() #

The fgets() function is used to read a single line from a file.

fgets() функцийг файлаас нэг мөр уншихад ашигладаг.

The example below outputs the first line of the “webdictionary.txt” file:

Доорх жишээнд “webdictionary.txt” файлын эхний мөрийг гаргана:

Example #

Жишээ #

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); echo fgets($myfile); fclose($myfile); ?>

Note: After a call to the fgets() function, the file pointer has moved to the next line.

Тэмдэглэл: fgets() функц руу залгасны дараа файлын заагч дараагийн мөрөнд шилжсэн.


PHP Check End-Of-File – feof() #

The feof() function checks if the “end-of-file” (EOF) has been reached.

feof() функц нь “файлын төгсгөлд” (EOF) хүрсэн эсэхийг шалгадаг.

The feof() function is useful for looping through data of unknown length.

feof() функц нь үл мэдэгдэх урттай өгөгдлийг давталт хийхэд ашигтай байдаг.

The example below reads the “webdictionary.txt” file line by line, until end-of-file is reached:

Доорх жишээнд “webdictionary.txt” файлыг файлын төгсгөл хүртэл мөр, мөрөөр уншина уу.

Example #

Жишээ #

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one line until end-of-file while(!feof($myfile)) { echo fgets($myfile) . "<br>"; } fclose($myfile); ?>

PHP Read Single Character – fgetc() #

The fgetc() function is used to read a single character from a file.

fgetc() функцийг файлаас нэг тэмдэгт уншихад ашигладаг.

The example below reads the “webdictionary.txt” file character by character, until end-of-file is reached:

Доорх жишээнд “webdictionary.txt” файлыг тэмдэгтээр нь файлын төгсгөл хүртэл уншина уу.

Example #

Жишээ #

<?php $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!"); // Output one character until end-of-file while(!feof($myfile)) { echo fgetc($myfile); } fclose($myfile); ?>

Note: After a call to the fgetc() function, the file pointer moves to the next character.

Тэмдэглэл: fgetc()  функц руу залгасны дараа файлын заагч дараагийн тэмдэгт рүү шилжинэ.


Complete PHP Filesystem Reference #

For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.

Файлын системийн функцийг бүрэн лавлахын тулд манай PHP файлын системийн лавлагаа руу орно уу.

Powered by BetterDocs

Leave a Reply