Read Files In PHP
PHP provides various functions to read data from a file. There are different functions that allow you to read all file data, read data line by line and read data character by character.
This function returns the number of bytes read on success, or FALSE and an error on failure. You can hide the error output by adding an "@" in front of the function name.
PHP file read functions are given below.
- fread()
- fgets()
- fgetc()
PHP Read File - fread()
The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.
Syntax
string fread (resource $file, int $length )
- $file represents file pointer that is created by fopen() function.
- $length represents the length of byte to be read.
PHP Read File Example
<?php
$filename = "Your Directory Path\fileName.txt";
$fp = fopen($filename, "r");//open file in read mode
$fileContents = fread($fp, filesize($filename));//read file
echo "<pre>$fileContents </pre>";//printing data of file
fclose($fp);//close file
?>
Output :
This is Php Tutorials
Online Learning Website
I Am Software Developer
PHP Read File - fgets()
The PHP fgets() function is used to read a single line from the file.
Syntax
string fgets ( resource $handle [, int $length ] )
PHP Read File - fgets() Example
<?php
$fp = fopen("Your Folder Path\myFile.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>
Output
this is first line
PHP Read File - fgetc()
The PHP fgetc() function is used to read single character from the file. To get all data using fgetc() function, use !feof() function inside the while loop.
Syntax
string fgetc ( resource $handle )
PHP Read File - fgetc() Example
<?php
$fp = fopen("Your Directory Path\fileName.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>
Output
this is first line this is another line this is third line
