PHP – File Reading

Posted by tutor | Posted in PHP Tutorial | Posted on 09-08-2010-05-2008

0

fread() Function

The fread function is used for getting data out of a file.

This function takes two parameters, again. The first parameter is a handle to the file you want to read and the second parameter is an integer to tell the function how much data, in bytes, it is supposed to read.

One character is of one byte. So, if you wanted to read the first five characters then you use five as the second argument.

    For eg:
    $sampleFile = “sample.txt”;
    $samplefile_handle = fopen($sampleFile, ‘r’);
    $data = fread($samplefile_handle, 6);
    fclose($samplefile_handle);
    echo $data;
    Output:
    PHP is

If you want to read the whole content from the file, then you will need the size of the file, which will give the idea how much content it has. To get the size of the file you can use the filesize function. This function returns the length of a file, in bytes. The filesize function takes only one argument ie the name of the file whose size we want to find.

    $samplefile_handle = fopen($sampleFile, ‘r’);
    $data = fread($samplefile_handle, filesize($sampleFile));
    fclose($samplefile_handle);
    echo $data;

    The feof() function is useful for looping through data of unknown length. For eg if we are searching for some string in the file.

    You can read from a file only when it is opened in read mode.

      if (feof($file)) echo “End of file”;

    Reading a File Line by Line

    The fgets() function is used to read a single line from a file.

    The file pointer moves to the next line in the file after each call to this function. The fgets function searches for the first occurrence of “\n” the newline character. If you did not write newline characters to your file, then this function might not work the way you expect it to.

    The example below reads a file line by line, until the end of file is reached:

      For eg:
      $file = fopen(“sample.txt”, “r”) or exit(“File opening failed!”);
      //Output a line of the file until the end is reached
      while(!feof($file))
      {
      echo fgets($file). ”
      “;
      }
      fclose($file);
      ?>

    Reading a File Character by Character

    The fgetc() function is used to read a single character from a file.

    The file pointer moves to the next character in the file after each call to this function.

    The example below reads a file character by character, until the end of file is reached:

      For eg:
      $file=fopen(“sample.txt”,”r”) or exit(“File opening failed!”);
      while (!feof($file))
      {
      echo fgetc($file);
      }
      fclose($file);
      ?>

Write a comment

Twitter Users
Enter your personal information in the form or sign in with your Twitter account by clicking the button below.