In this program, we are going to open, read and close a file using the functions fopen(), read(),
and fclose()
. to open a file we have to use the function fopen()
and we have to pass the argument which is the file name with extension and the mode of open for example if we are going to open the file for reading then the mode will be 'r' if it is for writing then the mode will be 'w' there six more modes like this. After opening the file we have to read the file for that we use the function fread()
in it we have to pass the arguments resource handle and length of the maximum number of bytes to be read. And at last, we have to close the file by using the function fclose()
with resource handle as the argument.
Syntax
fopen(string filename, string mode)
fread(resource handle, int length)
fclose(resource handle)
Step 1: First we have to open the file by using the function fopen("demo.txt", r) and assign it to the variable file
Step 2: To read the file we have to call the function fread($file,E_ALL) and assign it to the variable text
Step 3: Print the value of the variable text
Step 4: At last we have to close the file using the function fclose(file)
<?php
$file = fopen("demo.txt", "r");
$text = fread($file, E_ALL);
echo $text;
fclose($file);
?>
Hi! All welcome to learnetutorials.com