PHP Basic Tutorial
MySQL Connection
PHP Advanced
In PHP, files can be opened, read, and closed using various functions like fopen()
, fread()
, and fclose()
. These are essential for performing file operations safely and efficiently.
We will use the text file, "sample.txt", during the lessons:
The fopen()
function is used to open a file. It requires two parameters:
Try it yourself
The file may be opened in one of the following modes:
Modes |
Description |
---|---|
r |
Read-only. Starts at the beginning of the file. File must exist. |
r+ |
Read and write. Starts at the beginning of the file. File must exist. |
w |
Write-only. Opens and clears the contents. Creates a new file if it doesn't exist. |
w+ |
Read and write. Clears the contents of the file. Creates a new file if it doesn't exist. |
a |
Write-only. Opens the file and writes at the end (append). Creates the file if it doesn't exist. |
a+ |
Read and write. Opens the file in append mode. Creates the file if it doesn't exist. |
x |
Write-only. Creates a new file. Returns |
x+ |
Read and write. Creates a new file. Returns |
c |
Write-only. Opens the file if it exists or creates a new one. Does not delete existing data. |
c+ |
Read and write. Opens or creates a file without deleting its content. |
After opening a file, use fread()
to read its contents.
fread()
requires two parameters:
fopen()
).filesize()
.The following PHP code reads the "example.txt" file to the end:
It is important to close the file using fclose()
after reading or writing to free up resources.
The fclose()
requires the name of the file (or a variable that holds the filename) we want to close:
The fgets()
function in PHP is used to read a single line from an open file.
fgets(file, length)
file
(Required) → A valid file pointer, typically returned by fopen()
.length
(Optional) → The number of bytes to read. If not specified, it will read until it reaches a newline (\n
) or the end of the file (EOF
).he example below outputs the first line of the "example.txt" file:
Try it yourself
Note
After a call to the fgets()
function, the file pointer has moved to the next line.
The feof()
function in PHP is used to check whether the end of a file (EOF) has been reached.
feof(file)
file
(Required) → A valid file pointer returned by fopen()
or popen()
.true
if the end of the file (EOF) has been reached.false
if it hasn't reached the end of the file.Try it yourself
The fgetc()
function in PHP is used to read a single character from an open file. It is useful when you need to read a file character by character.
fgetc(file)
file
(Required) → A valid file pointer returned by fopen()
.false
on end of file (EOF) or error.Try it yourself