How to Read and Display Text Files in PHP - Step-by-Step Guide

New to PHP? Learn how to read text files and display their content in the browser using simple PHP functions. Step-by-step with working examples and explanations.

PHP Text File Reading

This tutorial is very easy and specially for the beginners. In this post we will learn how to open and read text file and  display its contents using PHP. The script logic is very easy to understand.

📘 Understanding File Handling in PHP (Before You Start)

Before reading text files, it’s important to understand that PHP provides built-in file handling functions which make working with files very easy. These functions allow you to open, read, write, and even create files dynamically on the server.

In this tutorial, we’re focusing only on reading files — but the same functions can be extended to manage any type of file operation. For example, you can use PHP to read log files, import data from text sources, or build an upload-and-view system for admin panels.

 

💡 Real-World Use Cases

Knowing how to read and display text files in PHP can be useful in several real-life applications. Here are a few examples where this script can be applied directly:

  • Displaying server logs: Many web apps generate log files (like error_log.txt), which can be read and shown to administrators for quick debugging.
  • Importing text-based data: If you have large text-based data (like product lists or student records), you can read it line by line and insert it into a database.
  • Simple CMS or content tools: Display static information or notes stored as text files without requiring a database connection.
  • Configuration readers: Load settings or credentials from .env or .txt files (though sensitive data should always be secured properly).

 

All file-related operations in PHP happen through something called a file pointer. When you open a file using fopen(), PHP returns a file pointer that keeps track of where you are inside the file. As you read each line or character, PHP moves this pointer ahead until it reaches the end of the file (EOF). We are going to be familiar with four simple file system functions of the PHP which are as below:

 

fopen()  - Opens file or URL

<?php
   $data = fopen("c:\\folder\\testing.txt", "r");
?>

 

feof()  - Tests for end-of-file on a file pointer

<?php
    $fp = fopen("testfile.txt", "r");
    while (!feof($fp)) {
     // do stuff to the current line here
    }
    fclose($fp);
?>

 

fgets()   - Gets line from file pointer

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

 

fgetc()   - Gets character from file pointer

<?php
    $fp = fopen('testfile.txt', 'r');
    if (!$fp) {
        echo 'Could not open file somefile.txt';
    }
    while (false !== ($char = fgetc($fp))) {
        echo "$char\n";
    }
?>

Now you are familiar with these functions so lets have a look how you can use them. First of all make simple form having one file upload control.

<html>
<body> 
 <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
   <input type="file" name="file" size="60" />
   <input type="submit" value="Read Content" />
 </form>
</body>
</html>

Notice the following about the HTML form above:

  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. multipart/form-data is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type="file" attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field

Now we will have to put some check for the uploaded file like if its uploaded or not, its type (.txt).

//Checking if file is selected or not
if ($_FILES['file']['name'] != "") {

//Checking if the file is plain text or not
if (isset($_FILES) && $_FILES['file']['type'] != 'text/plain') {
    echo "<span>File could not be accepted ! Please upload any '*.txt' file.</span>";
    exit();
}

Now we are going to open and read the uploaded file.

$file = fopen($fileName,"r") or exit("Unable to open file!");

// Reading a .txt file line by line
while(!feof($file)) {
    echo fgets($file). "";
}

//Reading a .txt file character by character
while(!feof($file)) {
    echo fgetc($file);
}

As we learnt that the feof() will test for end of file. fgets() method will read text file line by line, and fgetc() is used  for reading text file character by character. 

That it.! Simple script is ready. Let's have look at the complete script.

<html>
  <body> 
    <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
      <input type="file" name="file" size="60" />
      <input type="submit" value="Read Contents" />
    </form>
  </body>
</html>

<?php
if ($_FILES) {
    //Checking if file is selected or not
    if ($_FILES['file']['name'] != "") {
  
      //Checking if the file is plain text or not
      if (isset($_FILES) && $_FILES['file']['type'] != 'text/plain') {
          echo "<span>File could not be accepted ! Please upload any '*.txt' file.</span>";
          exit();
      } 
      echo "<center><span id='Content'>Contents of ".$_FILES['file']['name']." File</span></center>";
    
      //Getting and storing the temporary file name of the uploaded file
      $fileName = $_FILES['file']['tmp_name'];
    
      //Throw an error message if the file could not be open
      $file = fopen($fileName,"r") or exit("Unable to open file!");
     
      // Reading a .txt file line by line
      while(!feof($file)) {
        echo fgets($file). "";
      }
     
      //Reading a .txt file character by character
      while(!feof($file)) {
        echo fgetc($file);
      }
      fclose($file);
  } else {
      if (isset($_FILES) && $_FILES['file']['type'] == '')
        echo "<span>Please Choose a file by click on 'Browse' or 'Choose File' button.</span>";
    }
}
?>

 

📖 Recommended: PHP MySQL CSV Import Tutorial with Secure Code & Best Practices

PHP MySQL CSV Import — Secure & Scalable Import with Transactions and LOAD DATA INFILE (2025)

 

🧠 Step-by-Step Explanation

Let’s break down what happens behind the scenes when you upload and read a text file using PHP:

  1. User uploads the file: The browser sends the file to your PHP script through the $_FILES superglobal.
  2. PHP validates the file: You check if the file is not empty and ensure it’s a plain text file (text/plain).
  3. File is temporarily stored: The uploaded file is saved in a temporary directory, which you can access via $_FILES['file']['tmp_name'].
  4. File is opened using fopen(): You use fopen() to open it in read mode ("r").
  5. File is read using fgets() or fgetc(): You can now read it line by line or character by character and display it in the browser.
  6. Close the file: Finally, use fclose() to free up server resources.

This process ensures smooth file handling and avoids unexpected server memory issues during long file reads.

 

⚠️ Error Handling and Best Practices

When working with file uploads or file reads, you should always consider possible errors. Here are some helpful tips to make your code more robust:

  • Always check if the file exists using file_exists() before attempting to read it.
  • Handle upload errors using $_FILES['file']['error'] for safer debugging.
  • Use filesize() to verify that the file isn’t empty before processing.
  • Make sure to call fclose() after file operations to avoid memory leaks.
  • Restrict file uploads to a specific directory and avoid giving public write permissions.

Proper validation ensures your PHP script is not only functional but also secure and optimized.

 

🔁 Alternative PHP Functions You Can Try

Besides fgets() and fgetc(), PHP also provides a few other useful functions for reading file data quickly:

  • file_get_contents() – Reads the entire file into a string with one simple line.
  • readfile() – Outputs a file directly to the browser without manually looping through its contents.
  • file() – Reads the entire file into an array where each line becomes an array element.

For example:

<?php
$content = file_get_contents("sample.txt");
echo nl2br($content);
?>

This is the easiest way to read small text files where performance isn’t a concern. However, for large files, using fgets() in a loop is a better approach since it consumes less memory.

 

🔒 Security Considerations When Handling Files

File uploads always carry a potential risk, especially if not properly validated. Here are some important security measures to follow:

  • Never allow unrestricted file uploads — always check file type and size.
  • Rename uploaded files to avoid overwriting existing ones or running malicious code.
  • Store uploaded files outside the public web directory (e.g., in a secure uploads/ folder).
  • Do not execute or include uploaded files directly in PHP — always treat them as plain data.

Even though this tutorial deals with text files, it’s a good practice to apply these security habits consistently.

 

🚀 Performance Optimization Tips

If you are reading large text files, here are a few optimization ideas:

  • Read files in chunks using fgets() to prevent memory overload.
  • Use ob_flush() and flush() to display output progressively for better UX.
  • Compress static text files using GZIP when serving frequently accessed files.

These small tweaks can make a big difference when handling big data logs or reports.

 

🌐 Beyond Basics: Modern Use Cases

Today, reading text files in PHP is not limited to static pages. It’s often used for:

  • Reading CSV or log files for analytics dashboards
  • Parsing configuration files for automation tools
  • Integrating with REST APIs that store response data in flat text formats

So once you master these basic file functions, you can extend your knowledge to build data importers, parsers, or even lightweight content systems.

 

❓ Frequently Asked Questions

Q1: Can PHP read other file types like CSV or JSON using the same functions?
Yes, PHP can read any text-based file using the same functions. For JSON or CSV, you just need to parse it after reading using functions like json_decode() or str_getcsv().

Q2: What happens if the file doesn’t exist?
PHP will throw a warning like “failed to open stream: No such file or directory”. Always use file_exists() to check before reading.

Q3: Is it necessary to close the file using fclose()?
Yes! It releases the file handle from the server’s memory and ensures better performance.

 

🏁 Conclusion

By now, you’ve learned how to upload, open, and read text files using PHP. These are fundamental skills every PHP developer should know. Once you’re confident with text files, you can move on to reading structured files like JSON or CSV, which are often used in real-world applications.

This example might be simple, but it forms the foundation for building log viewers, import tools, and configuration readers — all powered by PHP’s built-in file system functions.

 

0 Comments
Leave a Comment