Current Location: Home> Latest Articles> PHP File Operations Basics: How to Read and Write File Contents

PHP File Operations Basics: How to Read and Write File Contents

gitbox 2025-06-18

PHP File Operations Basics: How to Read and Write File Contents

In web development, PHP is a widely-used server-side programming language that can effectively interact with web servers and connect HTML, CSS, JavaScript, and databases. File operations in PHP are one of the most fundamental skills for web developers. Mastering how to read and write files allows developers to implement many dynamic features. This article will explain commonly used file reading and writing methods in PHP and provide practical code examples.

1. File Reading

File reading is one of the basic functions in PHP. The following code demonstrates how to read a file's content using PHP:

            
$file = fopen("file.txt", "r");
if ($file) {
    while (($line = fgets($file)) !== false) {
        echo $line;
    }
    fclose($file);
}
            

In the above code, the fopen() function is used to open a file. The first parameter is the file path, and the second parameter specifies the file mode. 'r' indicates read-only mode. The fgets() function is then used to read each line of the file until the end is reached. Finally, the fclose() function is used to close the file.

2. File Writing

File writing in PHP is similar to file reading. The following code demonstrates how to create a file and write content to it:


$file = fopen("file.txt", "w");
if ($file) {
    fwrite($file, "Hello, world!");
    fclose($file);
}
            

In this example, the file is opened and set to write mode ('w'). If the file doesn't exist, PHP will create it. Then, the fwrite() function writes content to the file. Finally, fclose() is used to close the file and save the changes.

3. Appending to a File

If you want to append data to an existing file rather than overwrite its contents, you can use append mode ('a'):


$file = fopen("file.txt", "a");
if ($file) {
    fwrite($file, "Hello, world!");
    fclose($file);
}
            

The code above is similar to the previous writing example. The only difference is that append mode ('a') is used, which ensures that new content is added to the end of the file, without overwriting the existing data.

Conclusion

From the examples above, we can see that the most commonly used file operations in PHP are fopen(), fwrite(), and fclose(). These functions allow developers to read, write, and append to files. PHP file operations are powerful and flexible, and can meet a variety of needs. For more advanced file operations, it is recommended to consult the official PHP documentation for other useful functions.