SITERAW

Reading and Writing to Files

Variables are easy to use, but they're temporary. A variable's lifespan doesn't last long at all. But on your website, you'll probably want to save some data permanently.

For instance, you can't store forum messages in variables... because they get wiped as soon as the page finishes loading! If you want to save information long-term, you've got to write it to the hard drive. And what better way to do that than by creating files?

Luckily, PHP lets you save data into files on your server's hard drive.

Allowing File Access (chmod)

In order for PHP to create files, it needs access to a folder where it's allowed to write files. Basically, you have to give PHP permission to create and modify files — otherwise, it simply won't work.

To set those permissions, you usually have to change the CHMOD of the file or folder. That's the name of the command used to set permissions on Unix systems.

If you're on Windows, you've probably never heard of this — because it doesn't exist there (instead, we talk about "permissions," which are more or less the same thing). But your hosting server is most likely running Unix — at least for PHP. And on Unix, we use CHMOD to manage file access rights.

CHMOD is a 3-digit number you assign to a file (for example, 777). Depending on the number, the server will allow — or block — modifications to the file.

The catch? By default, most Unix systems don't allow PHP scripts to modify files. But that's exactly what we want to do! So how do we get around that? By changing the CHMOD, of course! 😄

You'll need... your FTP software! Yes, the same one you use to upload your pages to the web. 😉 Use whichever one you like — the process is pretty much the same.

Okay, without diving into a full Unix course, here's the basic idea: there are 3 types of users who can read/modify files.

  • The owner: the user who created the file. They usually have full rights — read, write, execute.
  • The first digit in CHMOD refers to their permissions. If it's 7, that means full access.
  • The group: not too relevant for us here. It's the group that the file owner belongs to.
  • This is the second digit in CHMOD (again, 7 in our example).
  • Public permissions: now this is the important part. Public permissions apply to everyone — including your PHP scripts.
  • This is the third CHMOD digit. By default it's 5, but for PHP to write, you need to set it to 7.

So if you set the CHMOD to 777, that means any program on the server (including PHP) has permission to modify the file. You'll need to set it to 777 if you want PHP to be able to write to the file.

You can also set the CHMOD of a folder. This controls whether PHP can read/write files inside that folder.

That'll come in handy if you need PHP to create or modify files in a specific directory.

If you want to dig deeper into CHMOD, I cover it in much more detail in my Unix systems course. Feel free to check out that chapter if you're curious.

Opening and Closing a File

Before you can read from or write to a file, you have to open it first.

Start by creating a file called counter.txt, for example. Upload it to your server using your FTP software, and set its CHMOD to 777, as we just learned.

Now, we're going to make a PHP script that works with counter.txt.

Your goal for today: count how many times a page has been viewed and save that number to the file.

Here's the basic setup:

<?php
// Step 1: Open the file
$myFile = fopen('counter.txt', 'r+');

// Step 2: Do stuff with the file...

// Step 3: Close the file when done fclose($myFile); ?>

There are three key steps here:

  • Open the file with fopen. This function returns a handle (a reference) that you'll store in a variable (here it's $myFile). You'll need that later to close the file.
  • fopen takes two arguments: the file name (counter.txt) and the mode in which you want to open it ('r+' in this case).

Here are the most useful modes:

ModeWhat it does
rOpen for reading only. You can't write to the file.
r+Open for reading and writing. You can read and write to the file. Very common.
aOpen for writing only. If the file doesn't exist, it'll be created automatically.
a+Open for reading and writing. Also creates the file if it doesn't exist. Note: the directory must have CHMOD 777! If the file already exists, new text will be added to the end.

  • In our case, we already created the file beforehand, so we don't need a+.
  • Do your read/write operations (we'll get to those shortly).
  • When you're done with the file, close it with fclose. Just pass it your file handle ($myFile) so PHP knows which one to close. :)

You're not limited to .txt extensions either. Name it whatever you like: counter.c, counter.num, or just plain counter.

Reading from a File

Now that we can open and close a file, let's learn how to read it (and later, how to modify it).

There are two main ways to read:

  • Character by character with fgetc
  • Line by line with fgets

Usually, we store one piece of data per line in our file. So we rarely use fgetc, since reading char by char is pretty clunky (you'd need a loop for that).

In our case, let's assume the file has only one line: the number of times the page has been viewed.

To retrieve this number, do the following:

<?php
// Step 1: Open the file
$myFile = fopen('counter.txt', 'r+');

// Step 2: Read the first line $line = fgets($myFile);

// Step 3: Close the file fclose($myFile); ?>

You pass fgets the file handle ($myFile), and it reads a full line (it stops at the first line break). So now, $line contains the first line of the file. :)

But what if my file has 15 lines? How do I read them all?

You'll need a loop. The first call to fgets gives you line 1. The second time through the loop, it gives you line 2, and so on.

It's not super efficient, but for small files, it works just fine. If you need to store a lot of information, a database is better.

Writing to a File

To write to a file, we use fputs. This function writes a line of text into your file.

Here's how to use it:

<?php fputs($myFile, 'Text to write'); ?>

However, it's important to know where you're writing in the file.

Here's how it works under the hood:

  • You open the file with fopen.
  • You read the first line using fgets.
  • At this point, the PHP "cursor" is at the end of that line. Let's say the file contains 78129. After reading, the cursor is like: 78129_.
  • If you do a fputs now, it'll write text at the end.
  • To avoid that, use fseek to move the cursor. For example: fseek($myFile, 0);
  • That resets the cursor to the beginning: _78129.

If you opened the file with 'a' or 'a+', anything you write always gets added to the end — fseek won't help there.

Now that the cursor is back at the beginning, you can safely write over the old content. The old text gets replaced.

Let's make that more concrete with an example that counts page views:

<?php
$myFile = fopen('counter.txt', 'r+');

$pageViews = fgets($myFile); // Read the first line (page view count) $pageViews++; // Increase the count by 1 fseek($myFile, 0); // Move the cursor back to the beginning fputs($myFile, $pageViews); // Write the new page view count

fclose($myFile);

echo '<p>This page has been viewed ' . $pageViews . ' times!</p>'; ?>

Not too bad, right? 😄

Let's break down the 4 main lines in the middle:

  • You read the current number of views from the file.
  • You increment that number by 1.
  • You move the cursor back to the beginning of the file.
  • You write the new number over the old one.

If you forgot to set the CHMOD of counter.txt to 777, you'll get this error:

Warning: fopen(counter.txt): failed to open stream: Permission denied

That means PHP wasn't allowed to open the file for writing. So yeah, don't skip that CHMOD step!

There you have it: how to open, read, write, and close a file in PHP. Sure, for large files this gets messy — but for small tasks like this, it works like a charm.

Now you officially know how to work with files! ^^

As you saw, it's quick and handy as long as you don't need to store too much in the file. Beyond that, MySQL is usually the smarter option. :)

There's a lot more you can do with files, but listing it all here would take forever. I encourage you to check out the official PHP documentation on file handling. It's a bit dry, but covers everything. You'll find functions to copy files, delete files, create folders, remove folders, and so on...

And remember — if you run into trouble, the SiteRaw forum is always there to help you out! 😉

How to Build a Website in HTML and CSS

Enjoyed this PHP & MySQL course?

If you liked this lesson, you can find the book "How to Build a Website in HTML and CSS" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete PHP & MySQL workshop with many exclusive bonus chapters.

More information