How to Read the File in PHP Language?

how-to-read-the-file-in-php-language

Objective

After reading this blog, you will be able to read files in PHP language. In the blog, you will get enough information about different ways 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 as follow:

Traditional Methods

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

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

Let’s see some traditional methods:

Recommended Read: Export PHP data to the .xls file

traditional-methods-to-read-the-php-file

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 the next one is filed open mode. To read a file we will use “r” as file open mode, “r” denotes “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 be 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);

?>

<strong>Recommended Read:</strong><a href="https://www.knowband.com/blog/tips/generate-qr-code-using-php/">Generate QR Code Using PHP</a>

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 ignores 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 names of an e-commerce plugin development and marketing firm. Our team of highly skilled and experienced IT professionals.

Recommended Read: How to Integrate Google reCAPTCHA with PHP?

Other Methods

other-methods-to-read-the-php-file

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

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’s see the difference between readfile&& @readfile.

Let’s try to open the 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.

Recommended Read:  Auto Loading in PHP

Good Practice!

If we are a programmer then we should always keep in mind our code can 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 the 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.

For all aspects related to eCommerce, we also offer custom development. Additionally, the top modules for Prestashop, Opencart, Magento, and Magento 2 are also available. A few of the top modules that Knowband offers are One Page SuperCheckout, Multi-Vendor Marketplace, Mobile App Builder, Spin and Win Module, Abandonded Cart and so on.  If you have any questions, contact us at support@knowband.com.

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..

One thought on “How to Read the File in PHP Language?

Leave a Reply

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