# 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”

1. Jadi inget masa lalu, awal2 belajar PHP