Comprehensive Guide to File Writing in PHP: From Basic fwrite to Efficient file_put_contents

Nov 20, 2025 · Programming · 9 views · 7.8

Keywords: PHP file writing | file_put_contents | fwrite function

Abstract: This article provides an in-depth exploration of two primary methods for file writing in PHP: the traditional fopen/fwrite/fclose combination and the efficient file_put_contents function. Through detailed code examples and comparative analysis, it explains usage scenarios, performance differences, and best practices to help developers choose the most appropriate file writing solution based on specific requirements.

Fundamental Concepts of File Writing

In PHP development, file operations are common requirements. Based on the core issue in the Q&A data, users encounter empty files after using fopen("lidn.txt","a") to create files. This stems from a misunderstanding of the file writing mechanism—using fopen alone only creates or opens files but does not automatically write content.

Traditional File Writing Method: fopen/fwrite/fclose Combination

As shown in Answer 2, the complete file writing process requires three steps:

<?php
$fp = fopen('lidn.txt', 'w');
fwrite($fp, 'Cats chase mice');
fclose($fp);
?>

Here, the second parameter of fopen specifies the opening mode: "w" indicates write mode (which clears existing content), while "a" indicates append mode (which adds content at the end of the file). The reference article further explains behavioral differences between modes, such as how using "w" mode overwrites existing file content.

Efficient File Writing Method: file_put_contents Function

As recommended in the best answer (Answer 1), file_put_contents provides a more concise solution:

<?php
file_put_contents('lidn.txt', 'Cats chase mice');
?>

This function internally encapsulates the complete process of fopen, fwrite, and fclose, achieving "one-click" file writing. According to PHP official documentation, this method performs comparably to the traditional approach but with cleaner, more readable code.

Comparative Analysis of Both Methods

Code Simplicity: file_put_contents completes file writing in a single line of code, whereas the traditional method requires three lines to handle opening, writing, and closing operations separately.

Functional Completeness: Both methods are functionally equivalent for basic file writing. However, the traditional method offers finer control, supporting features like multiple write operations and file locking.

Error Handling: The reference article mentions using or die() for error handling, applicable to both methods. file_put_contents returns the number of bytes written, facilitating more precise error judgment.

Practical Application Scenarios

For simple, one-time file writing needs, file_put_contents is highly recommended, such as for logging or saving configurations. Its code simplicity significantly enhances development efficiency.

For complex scenarios requiring multiple writes, stream processing, or special file locking, the traditional fopen/fwrite/fclose combination provides greater flexibility.

Special attention should be paid to file permissions, as noted in the reference article. Ensure the PHP process has write access to the target directory; otherwise, any write operation will fail.

Complete Example Code

Based on the Q&A data and reference article, here is a complete file writing example:

<?php
// Method 1: Using file_put_contents (Recommended)
$filename = "lidn.txt";
$content = "Cats chase mice";
$result = file_put_contents($filename, $content);

if ($result === false) {
    echo "File writing failed";
} else {
    echo "Successfully wrote {$result} bytes";
}

// Method 2: Using fwrite (Traditional Method)
$fp = fopen($filename, 'w');
if ($fp) {
    fwrite($fp, $content);
    fclose($fp);
    echo "File writing completed";
} else {
    echo "Unable to open file";
}
?>

Conclusion

PHP offers two primary methods for file writing, and developers should choose the appropriate one based on specific needs. file_put_contents is the preferred choice for most scenarios due to its simplicity and efficiency, while the traditional method remains indispensable when fine-grained control is required. Understanding the essential differences and applicable scenarios of these methods helps in writing more robust and efficient PHP code.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.