PHP: How Do I Read From a Text File?

Posted on in Categories , , , , , last updated June 25, 2012

How do I read from text file using PHP under Linux or UNIX?

PHP does supports the file reading and writing. You can open a file using the fopen() function. Once the file is open, you can use the fgets() function to read from the file.

For example, if you wish to open file called /tmp/file1.txt then following PHP code will help you to read file. fopen() will open fine in r (read) mode. Then while loop will open file using fgets() function till end of file:

php source code

<title>File read demo</title>
$file = "/tmp/file1.txt";
$f = fopen($file, "r");
while ( $line = fgets($f, 1000) ) {
print $line;

See fopen() and fgets() for more information.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

15 comment

  1. This works for me:

    if ($_FILES['fileUpload']['error'] == UPLOAD_ERR_OK               
          && is_uploaded_file($_FILES['fileUpload']['tmp_name'])) { 
      echo file_get_contents($_FILES['fileUpload']['tmp_name']); 

    Hope it helps.

    Edited by admin: added pre tags.

  2. hi, i want to ask a question that . it i have a test.txt file with this data .

    Student Table.
    1- student 1
    2- student 2
    3- student 3

    this file located in D:\test.txt …..
    how can i read this file on web page and show out put like first line as title and other lines are same as it is.

    plz help. sorry for bad english.
    Thanx in advance

Leave a Comment