Files are everywhere! Just about every piece of data on our computer is stored using files. For example, we could have a document saved into a
.jpeg, or a song as a
.mp4. Sometimes we can even have multiple files compressed into a single file such as a
.zip. These files are then organized into a structure of directories known as a file system.
As developers, it is common that we may want to work with files. Maybe we want our applications to open different PDF files or find and play a selected MP4 file. Many applications use files to store software configurations and activity logs. Learning to use programming to handle files is important to be able to write effective software! Don’t worry — PHP, as well as many other programming languages, have easy-to-use features to work with files.
To start to understand how PHP interacts with files, imagine we wanted to read a book (a sort-of real-world file). Before we can read a book, we first need to open it. When we’re finished reading, we will probably want to close the book. In PHP, to work with files, we can follow a similar process: open a file, perform some operation (such as reading or writing), and then close the file.
In this lesson, we will start to explore the basic operations of working with files in PHP. Specifically, we will learn to:
- Open and close a file
- Read the contents of a file
- Write to a file
- Append to a file
- Use PHP shorthand functions for file operations
- Retrieve important information about a file
- Deal with common file handling errors and bugs
Let’s get started!
The PHP code you’re looking at belongs to a file called
index.php. This file contains code that will use an array of strings and write each of them to a new file (
languages.txt) and print the result. Click Run to see PHP file handling in action! Note the new file that will be created and the contents inside of it. Don’t worry, we will learn what all of these new functions are in the next exercises.