Current Location: Home> Latest Articles> PHP File Operations Guide: Read, Write, and Manage Files with PHP Functions

PHP File Operations Guide: Read, Write, and Manage Files with PHP Functions

gitbox 2025-07-27

File Reading Operations

File reading operations are among the most common tasks in PHP, often used to retrieve the contents of a file. PHP provides multiple functions for reading files. Below are some of the commonly used functions:

file_get_contents()

The file_get_contents() function reads the content of a file and returns it as a string. The function takes the filename as its parameter.

Example usage:

$content = file_get_contents('file.txt');
echo $content;

This code will read the contents of file.txt and print it to the screen.

fgets()

The fgets() function reads a file line by line and takes a file handle as its parameter.

Example usage:

$handle = fopen('file.txt', 'r');
while ($line = fgets($handle)) {
    echo $line;
}
fclose($handle);

This code will read the content of file.txt line by line and output each line.

File Writing Operations

File writing operations allow you to save data into a file. PHP provides several functions for writing to files:

file_put_contents()

The file_put_contents() function writes data to a file. It takes two parameters: the filename and the content to be written.

Example usage:

$content = 'Hello, world!';
file_put_contents('file.txt', $content);

This code writes the string 'Hello, world!' into the file file.txt.

fwrite()

The fwrite() function writes data to an open file, taking two parameters: the file handle and the content to be written.

Example usage:

$handle = fopen('file.txt', 'w');
fwrite($handle, 'Hello, world!');
fclose($handle);

This code writes the string 'Hello, world!' into file.txt.

File Handling Functions

In addition to basic read and write operations, PHP provides several other useful file handling functions:

file_exists()

The file_exists() function checks whether a file exists. It takes the filename as a parameter.

Example usage:

$file = 'file.txt';
if (file_exists($file)) {
    echo 'File exists';
} else {
    echo 'File does not exist';
}

This code checks if file.txt exists and prints the appropriate message.

unlink()

The unlink() function deletes a file. It takes the filename as a parameter.

Example usage:

$file = 'file.txt';
if (file_exists($file)) {
    unlink($file);
    echo 'File deleted';
} else {
    echo 'File does not exist';
}

This code deletes file.txt and prints the result of the deletion.

Conclusion

This article covered common PHP file handling functions, including reading, writing, and deleting files, as well as file existence checking. These functions make it easy for developers to manage files efficiently.

Note: When performing file operations, it is essential to ensure that file permissions and paths are correct.