Everything you do when using computers is related to files and folders. The browser you’re using to view this webpage is a file on your device, and this webpage is a file on this website’s server, which means everything is a file one way or another. In this article, you will learn everything you need to know to build files and folder-related features in your PHP applications.
Prerequisites
To follow along with this article, you need to have a solid grasp of the basics of PHP. Knowledge of variables, functions, conditionals, etc., will come in handy. However, every concept and code example covered in this article will be adequately explained to ensure everything is clear.
File operations in PHP
File handling is an essential part of any web application, and all programming languages provide a way to perform these tasks in your applications. PHP is no exception, so it gives an extensive list of functions you can use when working with files in your applications. The following sections will explore these functions and what they allow you to do in your PHP applications.
Reading files in PHP
Reading files is the most common file-related task in programming. PHP provides different ways to do this in your applications, and we will be exploring them in the following sections.
Read the file into a string variable
PHP allows you to read files as strings with the file_get_contents
function. Here’s an example:
$fileContents = file_get_contents('file.txt');
echo $fileContents;
The code above returns all the content in the file.txt as a string or a warning if the file is unavailable in the directory.
Read file line by line
You can easily read a file line by line in PHP by using the fopen
function with a loop like this:
if (file_exists('file.txt')) {
$file = fopen('file.txt', 'r');
while (($line = fgets($file)) !== false) {
echo $line . '
';
}
fclose($file);
} else {
echo 'File does not exist';
}
The code above checks if the file exists using the file_exists
function and opens the file.txt file in read mode; it then uses a while loop and the fgets
function to read and print out the file line by line. Finally, after completing the loop, the code uses the fclose
function to close the file.
The code above will return the following based on my file.txt file:
This is a sample text file. It contains some text for testing purposes. You can add more text here.
Note: You should always check if a file exists before operating on it and close files after working on them. Doing these would help minimize the number of bugs you’ll have to fix.
Let’s explore the different file opening modes in the next section.
Understanding the file opening modes in PHP
The fopen
function in PHP is used to open files and returns a file pointer/resource that can be used for various file operations. The function accepts a filename and an optional mode string that specifies the intended file operation and other options. The following is a list of common mode options for fopen
.
r
(Read) – Open the file for reading. The file pointer is placed at the beginning of the file. If the file does not exist, it will return false.r+
(Read/Write) – Open the file for both reading and writing. The file pointer is placed at the beginning of the file. If the file does not exist, it will return false.w
(Write) – Open the file for writing. If the file does not exist, it will be created. If the file exists, its contents will be truncated. The file pointer is placed at the beginning of the file.w+
(Read/Write) – Open the file for both reading and writing. If the file does not exist, it will be created. If the file exists, its contents will be truncated. The file pointer is placed at the beginning of the file.a
(Append) – Open the file for writing. If the file does not exist, it will be created. The file pointer is placed at the end of the file, allowing you to append data without overwriting existing content.a+
(Append/Read) – Open the file for reading and writing. If the file does not exist, it will be created. The file pointer is placed at the end of the file.x
(Exclusive Create) – Open the file for writing only if it does not already exist. If the file exists,fopen
will return false.x+
(Exclusive Create/Read) – Open the file for reading and writing only if it does not already exist. If the file exists,fopen
will return false.c
(Open for Writing) – Open the file for writing. If the file does not exist, it will be created. Unlikew
, it does not truncate the file. The file pointer is placed at the beginning of the file.c+
(Open for Reading/Writing) – Open the file for reading and writing. If the file does not exist, it will be created. Unlikew+
, it does not truncate the file. The file pointer is placed at the beginning of the file.e
(Ephemeral) – Open the file in “ephemeral” mode. It behaves likew
but does not affect the file modification time. It was introduced in PHP 7.4.b
(Binary mode) – Appendb
to any of the above modes (e.g.,rb
,wb+
) to indicate binary mode, which is used when working with binary files.t
(Text mode) – Appendt
to any of the above modes (e.g.,rt
,w+t
) to indicate text mode, which is the default mode used for text files on most platforms.
Note: The behavior of fopen
may vary slightly between different operating systems. Also, some modes may have platform-specific nuances or restrictions. Always check the PHP documentation and consider error handling when using fopen
to ensure your code behaves as expected.
Reading .csv files in PHP
PHP provides a fgetcsv
function for handling .csv files in your PHP applications. You can read and parse .csv files like this:
if (file_exists('file.csv')) {
$csvFile = fopen('file.csv', 'r');
while (($data = fgetcsv($csvFile)) !== false) {
echo '
'; print_r($data); echo '
';
}
fclose($csvFile);
} else {
echo 'File does not exist';
}
The code above does the same thing as the previous one but prints the CSV data as an associative array. The code will return the following based on my file.csv file:
Array ( [0] => Name [1] => Age [2] => Email ) Array ( [0] => John Doe [1] => 30 [2] => john@example.com ) Array ( [0] => Jane Smith [1] => 25 [2] => jane@example.com ) Array ( [0] => Bob Johnson [1] => 35 [2] => bob@example.com )
Reading .json files in PHP
PHP enables you to read and decode .json files using the file_get_contents
and json_decode
functions like this:
if (file_exists('file.json')) {
$jsonString = file_get_contents('file.json');
$jsonData = json_decode($jsonString, true);
echo '
'; print_r($jsonData); echo '
';
} else {
echo 'File does not exist';
}
The code above will print out the content of the file.json file as an associative array like this:
Array ( [0] => Array ( [name] => John Doe [age] => 30 [email] => john@example.com [address] => Array ( [street] => 123 Main St [city] => Anytown [state] => CA ) [hobbies] => Array ( [0] => Reading [1] => Gardening [2] => Cooking ) ) [1] => Array ( [name] => Jane Doe [age] => 25 [email] => jane@example.com [address] => Array ( [street] => 123 Alao St [city] => Surulere [state] => LA ) [hobbies] => Array ( [0] => Crocheting [1] => Hunting [2] => Swimming ) ) )
Reading .xml files in PHP
PHP provides a simplexml_load_string
function that you can combine with the file_get_contents
to read .xml files in your applications. For example, you can parse and use the content of a .xml file as an array in your code like this:
if (file_exists('data.xml')) {
$xmlString = file_get_contents('data.xml');
$xml = simplexml_load_string($xmlString);
$json = json_encode($xml);
$array = json_decode($json, true);
echo '
'; print_r($array); echo '
';
} else {
echo 'File does not exist';
}
The code above prints out the content of the data.xml file as an associative array like this:
Array ( [person] => Array ( [0] => Array ( [name] => John Doe [age] => 30 [email] => john@example.com ) [1] => Array ( [name] => Jane Smith [age] => 25 [email] => jane@example.com ) ) )