Introduction
In this blog, I will demonstrate how to read, write, and delete a file using PHP web programming language. Before we create, read, write, and delete a file, we need to understand some PHP functions and file modes carefully. These functions and modes are described below.
File modes
File modes specify the access type of your file.
| Mode | Description |
| r | Open a file for reading only. File pointer starts at the beginning of the file. |
| r+ | Open a file for reading and writing. File pointer starts at the beginning of the file. |
| w | Open a file for writing only. File pointer starts at the beginning of the file. |
| w+ | Open a file for reading and writing. File pointer starts at the beginning of the file. |
| a | Open a file for writing only. File pointer starts at the end of the file. |
| a+ | Open a file for reading and writing. File pointer starts at the end of the file. |
fopen(argu1,argu2) function
The fopen() function is used for opening a file. It takes two arguments - file path, and file mode. For example -
- $file_name = "D:/test.txt"; // file path
- $file = fopen($file_name, "r");
fwrite(argu1,argu2) function
The fwrite() function is used for writing a file. It takes two arguments - first, we need to specify a file pointer and second, specify our string that we want to write. For example -
- fwrite($file,"Hello world!");
fread(argu1,argu2) function
The fread() function is used for reading a file. It takes two arguments - a file pointer, and the length of the file. For example -
- $size = filesize($file_name ); //return length of the file
- $text = fread( $file, $size );
Note
The filesize() function returns the size of a file in bytes.
fclose(argu1) function
The fclose() function is used for closing a file. It takes one argument that holds an opened file pointer. For example -
- fclose($file)
unlink(argu1,argu2) function
The unlink() function is used for deleting a file. It takes two arguments - filename, and context. For example -
- unlink($file_name);
Note
The second argument, context, is an optional parameter that can be used for modifying the nature of stream or file.
File Write
After opening a file using fopen() function, the file can be written using the fwrite() function.
Example

Join the conversation! Your thoughts help the community grow.