Reading From file in php
How to Read a file using php?
Explanation
Reading and printing the contents in a file.
For an example we will use the file
test.txt to explain it
Step 1:Define the file name in to a variable
Example:
$file = "./test.txt";Step 2:We will open a stream (connection) with the file using the method or php function
fopen('filename','type')Example:
$open = fopen($file, "r");The method fopen takes two arguments, first the file name and second argument that determines the file-opening mode. To read a file it should be 'r'.
Step 3:Now we will find the size of the file using the php method
filesize('filename');
Example:
$fsize = filesize($file);This method takes the file name as argument and returns the size of the file in Bytes.
Step 4:We will read the content in the file using the php function
fread('stream','size')Example:
$fsize = fread($open,$fsize);We have passed two arguments to the method fread(). The first argument is the stream obtained in step2. The second argument is the size that has to be read from the file. To read the full file we have pass the full size of the file.
Example Code:
<?php
$file = "./test.txt";
$open = fopen($file, "r");
$size = filesize($file);
$count = fread($open, $size);
echo($count);
?>
The Result is
Name - HIOX INDIA Topic - tutorials