PHP File Open/Read/Close
This is used 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.
Example - file open
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 |
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 |
PHP Read File - fread()
The fread() function reads from an open file.
Syntax
fread($myfile,filesize("webdictionary.txt"));
PHP Close File - fclose()
The fclose() requires the name of the file we want to close.
Syntax
$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.
Example - read single line read
PHP Check End-Of-File - feof()
The feof() function checks if the "end-of-file" (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
Example - check end of file
PHP Read Single Character - fgetc()
This function is used to read a single character from a file.