How to read the file in PHP language?

The objective of the blog

After reading this blog, you will able to read file in PHP language. In the blog, you will get enough information about different way used in PHP to read a file.

Let’s learn about the file reading method in the PHP

PHP provides various type of methods to read the file are as follow:

Traditional Methods

In this type of method to read a file, we have to follow 3 step.

  1. Open the file.
  2. Read the file.
  3. Close the file.

Let’s see some traditional methods:

fopen():

To read a file we need to open a file using fopen(). In fopen(), we have to pass to 2 parameters i.e. first is the file path and next one is file open mode. To read a file we will use “r” as file open mode, “r” denotes for “read mode”.

$file = fopen("test.txt", "r") or die("Unable to open file!");

feof()

This method checks whether you have already read to the end of the file. This returns true till the last line of the file gets read and once we cross the last line it returns false. We use this method in a loop to read a file from the first line to the last line.

 

$file = fopen("test.txt", "r") or die("Unable to open file!");

while(!feof($file)) {

//your processing

}

fclose()

We use this method to close a file after reading the file. After closing a file we will no longer able to read that file.

 

$file = fopen("test.txt", "r") or die("Unable to open file!");

while(!feof($file)) {

//your processing

}

fclose($file);

fgets()

We use this method to read a file line by line.It collects a single line of data from your file and returns it as a string. And from there either you can print the line or you can process the same as per your requirement.

 

<?php

$file = fopen("test.txt", "r") or die("Unable to open file!");

while(!feof($file)) {

echo fgets($file) . "<br>";

}

fclose($file);

?>

fread()

We use this method if we want to read a file in a limited size. We have to pass a size limit in bytes in this method and then this method read the file up to a given size limit and ignore the rest part of the file.

If we want to read a file up to4,096 bytes (4 KB), we will write the code as –

 

$file = fopen("test.txt", "r") or die("Unable to open file!");

$data = fread($file, 4096);

Note: No matter what number you specify, fread will not read more than 8,192 bytes (8 KB). Assuming that the file is no bigger than 8 KB, the code below should read the entire file into a string.

 

<?php

$file = fopen("test.txt", "r") or die("Unable to open file!");

$data = fread($file, filesize("test.txt"));

fclose($file);

?>

fgetss()

This function is similar to the fgets() functionbut strips away any HTML or PHP tags it finds, leaving only plain text.

Code:

 

<?php

$file_handle = fopen("test.txt”, "r");

while (!feof($file_handle)) {

echo fgetss($file_handle);

}

fclose($file_handle);

?>

test.txt

 

<html>

<head>

<title></title>

</head>

<body>

<div class="editor-content" style="text-align: left">

<p>Knowband is one of the leading name as an e-commerce plugin development and marketing firm.</p>

<p> </p>

<p>Our team of highly skilled and experienced IT professionals.</p>

</div>

</body>

</html>

Output:

Knowband is one of the leading name as an e-commerce plugin development and marketing firm.Our team of highly skilled and experienced IT professionals.

Other Methods

PHP also provides various other methods for file handling that we can use for different purpose.

file_get_contents()

This method can be used to collect all the data from a file as a string. For example, how can we collect all the data from our webpage? You have seen the fgets() example using a loop. But how we you make this more straightforward? We can easily do the same with the file_get_contents(). We do not need to open or close a file to read. On failure, file_get_contents() will return false.

 

<?php

$file= file_get_contents("https://www.knowband.com/");

echo $file;

?>

readfile()

The readfile function dumps the entire contents of a file or Web page to the default output buffer. By default, this command prints an error message if it fails.To avoid this behavior we use @readfile()

Let see the difference between readfile&& @readfile.

Let’s try to open a wrong file by readfile:

 

<?php

$file= readfile("wrong_test.txt");

if(!$file){

echo 'File not found.';

} else{

echo $file;

}

?>

Output

( ! ) Warning: readfile(wrong_test.txt): failed to open stream: No such file or directory
Call Stack

File not found.

Now replace readfile with @readfile and we will get the output as:

File not found.

Good Practice!

If we are a programmer then we should always keep in the mind our code has the capability to handle the error or condition. There might be a chance the file that we are going to read was moved from the path or permission for the file has been changed and hence you are unable to get the content. So good practice says before reading a file we should check if the file exists and file has read permission.

 

<?php

$file = "test.txt";

if (file_exists($file) && is_readable($file)) {

$f = fopen($file, "r");

# Processing

fclose($f);

}

?>

Summary

If have any PHP ecommerce application like PrestaShop, OpenCart, Magneto etc. you can use the codes to reading the file as per your requirements.

Joe Parker

We boast of the best in the industry plugins for eCommerce systems and has years of experience working with eCommerce websites. We provide best plugins for platforms like - Magento, Prestashop, OpenCart and Shopify . We also provide custom module development and customization services for the website and modules..

Leave a Reply

Your email address will not be published. Required fields are marked *