PHP supports various modes of opening a file. The fopen() function is used to open a file in PHP. In general, fopen() function accepts two parameters:
Filename: This parameter specifies the name of the file to be opened.
Mode: This parameter specifies the mode in which the file should be opened.
resource fopen ( string $filename , string $mode )
The “a” or “a+” modes of fopen() function is used to append data into a file. The “a” mode opens a file in write only mode. While “a+” mode opens a file in read write mode. Both the modes continues writing in the existing file or creates a new file if it doesn’t exist. In both case, the pointer starts from the end of the file.
fwrite() function:
To write a file in PHP, fwrite() function is used.
Syntax:
int fwrite ( resource $handle , string $string )
Example:
//phpfile.txt: Hello!I am the first line.//
<!DOCTYPE html> <html> <body> <?php $samplefile = fopen("phpfile.txt", "a"); fwrite($samplefile, " And I am the second line."); fwrite($samplefile, " Hey, I am the third one."); $samplefile = fopen("phpfile.txt", "r"); echo fread($samplefile, filesize("phpfile.txt")); fclose($samplefile); ?> </body> </html> |
Output
Hello!I am the first line. And I am the second line. Hey, I am the third one. |