PHP File System

Working with Files in PHP

PHP, being a server-side language, enables manipulation of files and directories stored on the web server. This guide teaches you how to create, access, and modify files using PHP's file system functions.

Opening a File with PHP fopen() Function

To interact with a file, you must first open it. The PHP fopen() function is employed for this purpose. Its basic syntax is:

fopen(filename, mode)

The first parameter, filename, specifies the name of the file to be opened, while the second parameter, mode, determines how the file should be accessed. For example:

<?php
$handle = fopen("data.txt", "r");
?>

The file can be opened in various modes:

Modes Functionality
r Opens the file for reading only.
r+ Opens the file for reading and writing.
w Opens the file for writing only and clears its contents. If the file doesn't exist, PHP tries to create it.
w+ Opens the file for reading and writing, clearing its contents. If the file doesn't exist, PHP tries to create it.
a Appends to the file, preserving existing content. Opens the file for writing only. If the file doesn't exist, PHP tries to create it.
a+ Appends or reads from the file. Opens the file for reading and writing, preserving existing content. If the file doesn't exist, PHP tries to create it.
x Opens the file for writing only. Returns FALSE and generates an error if the file already exists. If the file doesn't exist, PHP tries to create it.
x+ Opens the file for reading and writing, behaves like 'x' if the file exists.

If you attempt to open a non-existent file, PHP will issue a warning. To avoid these warnings, it's advisable to first check whether a file or directory exists using the PHP file_exists() function before attempting to access it.

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Attempt to open the file
$handle = fopen($file, "r");
} else{
echo "ERROR: File does not exist.";
}
?>

Tip: File and directory operations can encounter errors. It's recommended to incorporate error checking in your scripts to handle potential errors effectively. For guidance, refer to the tutorial on PHP error handling.


Closing a File with PHP fclose() Function

When you're done working with a file, it's important to close it properly. This is done using the fclose() function in PHP, as demonstrated below:

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");

/* Some code to be executed */

// Closing the file handle
fclose($handle);
} else{
echo "ERROR: File does not exist.";
}
?>

Note: While PHP automatically closes all open files when a script ends, it's considered good practice to manually close files after you've finished performing operations on them.


After learning how to open and close files, the next step is reading data from them. PHP provides functions to read from a file, allowing you to read from a single character up to the entire file in one go.

Reading a Fixed Number of Characters

The fread() function is used to read a specified number of characters from a file. Its syntax is:

fread(file handle, length in bytes)

This function requires two parameters: the file handle and the number of bytes to read. For example, if you read 20 bytes from a file named "data.txt" that contains the text "The quick brown fox jumps over the lazy dog," including spaces, you would use:

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");

// Read fixed number of bytes from the file
$content = fread($handle, "20");

// Closing the file handle
fclose($handle);

// Display the file content 
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>

The example above will display the following result:

The quick brown fox

Reading the Entire File Content

To read the entire content of a file, you can combine the fread() function with the filesize() function. The filesize() function retrieves the size of the file in bytes.

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Open the file for reading
$handle = fopen($file, "r") or die("ERROR: Cannot open the file.");

// Reading the entire file
$content = fread($handle, filesize($file));

// Closing the file handle
fclose($handle);

// Display the file content
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>

The example above will display the following output:

The quick brown fox jumps over the lazy dog.

An efficient method to read the entire content of a file in PHP is using the readfile() function. This function reads and outputs the contents of a file without the need to explicitly open it. The following example achieves the same result as the previous example:

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Reads and outputs the entire file
readfile($file) or die("ERROR: Cannot open the file.");
} else{
echo "ERROR: File does not exist.";
}
?>

The example above will output:

The quick brown fox jumps over the lazy dog.

Another method to read the entire content of a file without explicitly opening it is using the file_get_contents() function. This function takes the file path as an argument and reads the entire file into a string variable. Here's an example:

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Reading the entire file into a string
$content = file_get_contents($file) or die("ERROR: Cannot open the file.");

// Display the file content 
echo $content;
} else{
echo "ERROR: File does not exist.";
}
?>

Another approach to retrieve all data from a file is PHP's file() function. It functions similarly to file_get_contents() but returns the file contents as an array of lines rather than a single string. Each element in the array corresponds to a line in the file.

To work with the file data, you would iterate through the array using a foreach loop. Below is an example that reads a file into an array and then displays its contents using the loop:

<?php
$file = "data.txt";

// Check the existence of file
if(file_exists($file)){
// Reading the entire file into an array
$arr = file($file) or die("ERROR: Cannot open the file.");
foreach($arr as $line){
echo $line;
}
} else{
echo "ERROR: File does not exist.";
}
?>

Writing Files Using PHP fwrite()

Similarly, you can write data to a file or append to an existing file using the PHP fwrite() function. The basic syntax of this function is:

fwrite(file handle, string)

The fwrite() function requires two parameters: a file handle and the string of data to write. Below is an example demonstrating its usage:

<?php
$file = "note.txt";

// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";

// Open the file for writing
$handle = fopen($file, "w") or die("ERROR: Cannot open the file.");

// Write data to the file
fwrite($handle, $data) or die ("ERROR: Cannot write the file.");

// Closing the file handle
fclose($handle);

echo "Data written to the file successfully.";
?>

In the previous example, if the "note.txt" file doesn't exist, PHP will create it automatically and write the data. However, if "note.txt" already exists, PHP will overwrite its contents before writing the new data. To append data to the file and preserve existing contents, use the mode a instead of w in the example.

Alternatively, you can use the file_put_contents() function, which is similar to file_get_contents() and provides a straightforward way to write data to a file without opening it. This function takes the file name, path, and the data to be written as parameters. Here's an example:

<?php
$file = "note.txt";

// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";

// Write data to the file
file_put_contents($file, $data) or die("ERROR: Cannot write the file.");

echo "Data written to the file successfully.";
?>

If the file specified in the file_put_contents() function already exists, PHP will overwrite it by default. To preserve the file's contents, you can use the special FILE_APPEND flag as a third parameter in the file_put_contents() function. This flag appends the new data to the file instead of overwriting it. Here's an example:

<?php
$file = "note.txt";

// String of data to be written
$data = "The quick brown fox jumps over the lazy dog.";

// Write data to the file
file_put_contents($file, $data, FILE_APPEND) or die("ERROR: Cannot write the file.");

echo "Data written to the file successfully.";
?>

Renaming Files with PHP rename() Function

You can change the name of a file or directory using PHP's rename() function, as shown in the following example:

<?php
$file = "file.txt";

// Check the existence of file
if(file_exists($file)){
// Attempt to rename the file
if(rename($file, "newfile.txt")){
echo "File renamed successfully.";
} else{
echo "ERROR: File cannot be renamed.";
}
} else{
echo "ERROR: File does not exist.";
}
?>

Removing Files with PHP unlink() Function

To delete files or directories in PHP, you can use the unlink() function, demonstrated in the following example:

<?php
$file = "note.txt";

// Check the existence of file
if(file_exists($file)){
// Attempt to delete the file
if(unlink($file)){
echo "File removed successfully.";
} else{
echo "ERROR: File cannot be removed.";
}
} else{
echo "ERROR: File does not exist.";
}
?>

In the next chapter, we will explore parsing directories or folders in PHP.


PHP Filesystem Functions

The table below summarizes various PHP filesystem functions that are useful for dynamically reading and writing files:

Function Description
fgetc() Reads one character at a time from a file.
fgets() Reads one line at a time from a file.
fgetcsv() Reads a line of comma-separated values from a file.
filetype() Returns the type of the file.
feof() Checks if the end of the file has been reached.
is_file() Checks if the given path is a regular file.
is_dir() Checks if the given path is a directory.
is_executable() Checks if the given file is executable.
realpath() Returns the canonicalized absolute pathname.
rmdir() Removes an empty directory.

For more details, refer to the PHP filesystem reference for a comprehensive list of PHP filesystem functions.