Learn How to Read and Display Text File Content in PHP

Reading and displaying text file content in PHP doesn't have to be a headache. Discover how to do it with ease in our simple and straightforward tutorial.

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. 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>";
    }
}
?>