What Are Different Functions To Read A File Using PHP

admin_img Posted By Bajarangi soft , Posted On 22-09-2020

PHP provides various functions to read data from the file. Different functions allow you to read all file data, read data line by line, and read data character by character.

How to read a file in PHP

PHP file read functions are given below:

  • fread()
  • fgets()
  • fgetc()
 

1.PHP fread() Function

The fread() reads from an open file.The function will stop at the end of the file or  file Reading stops when length bytes have been read.
Syntax for  fread() Function

fread(file, length)

Parameter   Description

file     Specifies the open file to read from
length   Specifies the maximum number of bytes to read

Example(1)

<?php
$file = fopen("myfile.txt","r");
fread($file,"10");//reads only 10 byte or we can give filesize function
fclose($file);
?>

above example fread function  reads only 10 bytes from myfile.text


2.PHP fgets() Function
The fgets() function returns a line from an open file.
Syntax for  fgets() Function.

fgets(file, length)

Parameter   Description

file     Specifies the open file to return a line from
length  Specifies the number of bytes to read. Reading stops when length-1 bytes have been reached,or on EOF.

Example(1)

<?php
$file = fopen("myfile.txt","r");
echo fgets($file);
fclose($file);
?>

In above example fgets function read one line from the myfile.text open file untill reaches length-1.
 


3.PHP fgetc() Function
The fgetc() function returns a single character from an open file.

Syntax for  fgetc() Function.

fgetc(file)

Parameter   Description

file    Specifies the open file to return a single character from

Example(1)

<?php
$file = fopen("myfile.txt","r");
echo fgetc($file);
fclose($file);
?>

In above example fgetc function reads single character from  myfile.txt  open file.
 


Complete code of read file function.

<!DOCTYPE html>
<html>
<head>
    <title>what are the different functions to read file in PHP</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>

<body>
<div class="container">
    <br>
    <br>
    <br>
    <div class="text-center">
        <h1>PHP Read a file in  different Function</h1>
    </div>
    <br>
    <br>
    <h2></h2>
    <div class="well">
        <?php
        $file = fopen("myfile.txt","r");
        echo "<h1>".fread($file,"10")."</h1>";
        fclose($file);

        echo "<br>";
        $file = fopen("myfile.txt","r");
        echo "<h1>".fgets($file)."</h1>";
        fclose($file);

        echo "<br>";

        $file = fopen("myfile.txt","r");
        echo "<h1>".fgetc($file)."</h1>";
        fclose($file);
        ?>
    </div>
    <br>
</div>
</body>
</html>

Related Post