Get up to 80 % extra points for free! More info:

Lesson 2 - Working with text files in PHP - Online course

In the previous lesson, Introduction to work with files in PHP , we learned what types of files exist and how to work with paths to those files. In this lesson, we will also look at how to work with unstructured plain text in PHP.

Although we will focus primarily on working with unstructured text files in this lesson, the functions we will learn to use here will be used in other lessons when we work with structured files too.

Ways to read and write files in PHP

There are two ways to read and write files in PHP:

  • using single-purpose functions and
  • using resources.

The advantage of the first method is its simplicity and speed. PHP has functions, that can read or write the entire contents of a file when called. However, if we want to work with sections of large files or work with a CSV file directly during reading and writing to it, this abstraction turns into a disadvantage. In these cases, we use resources. However, we will get acquainted with the second method in the next lesson.

Working with files using single-purpose functions

We will now get familiar with single-purpose functions.

file_put_contents() - writing a string to a file

Before we learn to read a file, let's learn how to create such a file and how to write some text in it. file_put_contents() is used to write a string to a file. The first argument takes a path to a file that we want to write to and the second argument is the text string that we want to write. If the target file does not exist, PHP will try to create it:

$file = "my_text.txt";
$text = "Hello!<br>\nThis is the text, that'll appear in our file. :-)";

file_put_contents($file, $text);

The contents of the my_text.txt file after running the script should be as follows:

Hello!<br>
This is the text, that'll appear in our file :-)

Error handling

Errors can occur during program execution, and programs working with files are no exception. The file_put_contents() returns the number of bytes written, but if an error occurs, it returns a boolean value of false. In the example above, the code for writing to the file should look like this:

$result = file_put_contents($file, $text);

if($result === FALSE) {
  echo "An error occurred while writing to the file !";
} else {
  echo "The File was successfully written!<br>Written bytes count: ", $result;
}

The browser should show you this:

file_put_contents()
file_put_conten­ts.php

In case of an error, the following message should appear:

file_put_contents() - ERROR
file_put_conten­ts.php

We can notice that we use the === operator, or the strict comparison operator, to compare the return value and the boolean value false. It ensures that the values being compared must not only be "same", but must also be of the same data type. This is important because the file_put_contents() function could "write" even 0 bytes, which does not necessarily indicate an error case. If we use the == operator (loose comparison operator), which we probably already know well, PHP, as a weakly typed language, would evaluate that 0 == false and we would have a hard-to-find bug in our program.:-)

Write error due to insufficient permissions

If we run the script on our own server and it ends with an error, the script probably does not have permission to write to the file. If the file already exists, we must grant the user account under which PHP is running write permission to the file. If the file does not exist yet, the user must be given write access to the folder in which the file will be created. If our server uses the Linux operating system, the issue of permissions is discussed in the lesson Linux Terminal (Bash) - Permissions, Installation and Processes in the course Linux Basics:-)

Adding content to a file (append mode)

If the file already exists and has some content, function file_put_contents() deletes it and creates a new file by default. If we wanted to create a guest book, this behaviour would be undesirable. However, the function offers us an append mode, in which new content is added to the end of the existing one. We can use this mode by passing the FILE_APPEND constant to the function as the third argument:

$result = file_put_contents($file, $text, FILE_APPEND);

File locking

If we had a lot of visitors on our website and everyone tried to write something to the same file, it could happen that writing to it took place more times at once and our file would be damaged. We can prevent this by passing the LOCK_EX constant as the third argument to the function. The write operation will be atomic as follows (i.e. all writes will take place one after the other, not at once):

$result = file_put_contents($file, $text, LOCK_EX);

If we want to combine append mode with locking, we combine the two constants using the bitwise OR (|) operator:

$result = file_put_contents($file, $text, FILE_APPEND | LOCK_EX);

file_get_contents() - reading a file into a string

We already created the file, so we can now read it. The file_get_contents() takes the contents of the file whose path we pass in the first argument, reads it whole, and returns its contents to us as a string. All you need to do is passing a single argument, which is the file name. The function returns either the read data as a string or false in case of an error:

$file = "my_text.txt";

$text = file_get_contents($file);

if($text === FALSE) {
  echo "An error occurred while reading the file!";
} else {
  echo "The file was successfully loaded!<br />File contents:<br />", $text;
}

The output of the script will look like this:

file_get_contents()
file_get_conten­ts.php

Since an empty string is also taken as false, the === operator is used here to check for errors.

file() - reading a file line by line into an array

The file() function works in the same way as file_get_contents(), except that it does not read the contents of the file into a string, but divides it into lines and returns an array of those lines. For example, if we had comments about our article stored in a file and each of them was on a separate line, this function would be more useful than file_get_contents(), because we would probably like to wrap individual comments in some HTML tags before outputting them, etc .:

$file = "my_text.txt";

$lines = file($file);

if($lines === FALSE) {
  echo "An error occurred while reading the file !";
} else {
  foreach($lines as $i => $line) {
    echo "Line n. ", ($i + 1), ": ", $line, "<br />";
  }
}

Output:

file()
file.php

readfile() - outputting a file directly to the browser

Sometimes we may not want to process the content of a text file in any way and just want to output it to a visitor of our website. The advantage of the readfile() function over the previously mentioned ones is that it can work with very large files. There is no intermediate step in the form of writing text to a variable (= to RAM), which has a limited size compared to disks. For example, if we wanted to output a database with several gigabytes in size, we would not be able to do so with the previously mentioned functions, but readfile() function would make it possible:-) :

$file = "my_text.txt";

$result = readfile($file);

if($result === FALSE) {
  echo "An error occurred while outputting the file!";
} else {
  echo "<br /><br /The file was outputted!<br />Outputted bytes: ", $result;
}

Output:

readfile()
readfile.php

As we can see, the variable $result will only contain the number of bytes read, while the content of the file itself ends up in the browser:-)

The source code with the examples from this lesson can be downloaded below.

In the next lesson, Working with CSV files in PHP , we will learn to work with files using resources and with structured files in CSV format. We will apply the knowledge in a practical example - a simple web task:-)


 

Did you have a problem with anything? Download the sample application below and compare it with your project, you will find the error easily.

Download

By downloading the following file, you agree to the license terms

Downloaded 2x (1.55 kB)
Application includes source codes in language PHP

 

Previous article
Introduction to work with files in PHP
All articles in this section
Working with files in PHP
Skip article
(not recommended)
Working with CSV files in PHP
Article has been written for you by Jan Štěch
Avatar
User rating:
No one has rated this quite yet, be the first one!
As an author I'm interested in PHP for web development, I'm also trying to improve in C#
Activities