PHP File Open, Read and Close

0 0
Read Time:1 Minute, 24 Second

PHP Open File – fopen()

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:

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.

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

ModesDescription
rOpen a file for read only. File pointer starts at the beginning of the file
wOpen 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
aOpen 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
xCreates 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

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %