File Handling in PHP: Read/Write To And From Text File

As a simple data storage alternative to Database Management System (e.g. MySQL) in PHP we can use plain text file. For example, a plain text file to store page counter information.

Below is an example on how to store a simple string (text) into a text (.txt) file:

<?php
  $data = 'some text';
  $fp = fopen('counter.txt', 'w');
  if($fp) {
    fwrite($fp, $data);
    fclose($fp);
  }
?>

Assuming a file named counter.txt exists in current directory, script below shows how we can read all text contained inside file:

<?php
  $fp = fopen('counter.txt', 'r');
  if($fp) {
    $data = fread($fp, filesize('counter.txt'));
    fclose($fp);
  }
  echo $data;
?>

 

One thought on “File Handling in PHP: Read/Write To And From Text File

Leave a Reply

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

*

CAPTCHA Image

*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>