fwrite is a function for writing data to a file. Its basic usage is as follows:
$fp = fopen('log.txt', 'w');
fwrite($fp, "Logging begins\n");
fclose($fp);
In this example, we open a file called log.txt and write a line of text to it. If the file does not exist, fopen will automatically create it.
Although fwrite is very direct, when writing structured or formatted data, it is not elegant to splice strings alone, and the code is not easy to maintain.
vfprintf is a variant of fprintf that allows us to output using format control characters and parameter arrays. This is great for dynamically generating formatted strings. For example:
$fp = fopen('report.txt', 'w');
$data = ['John Doe', 28, 3.75];
vfprintf($fp, "Name: %s, age: %d, score: %.2f\n", $data);
fclose($fp);
The output will be:
Name: John Doe, age: 28, score: 3.75
The benefits of this approach are:
Maintain consistency of the output structure
Easy to batch generate content based on format templates
Format control characters are safer and clearer than string stitching
In actual development, we usually use fwrite with vfprintf to implement conditional control or more complex logic.
For example, suppose we want to write a set of user activity records, and the record also contains access links:
$fp = fopen('activity.log', 'a');
$users = [
['Alice', 'login', 'https://gitbox.net/user/alice'],
['Bob', 'upload', 'https://gitbox.net/files/12345'],
['Charlie', 'download', 'https://gitbox.net/files/67890']
];
foreach ($users as $entry) {
list($name, $action, $url) = $entry;
$line = sprintf("[%s] user %s Performed: %s,Details: %s\n", date('Y-m-d H:i:s'), $name, $action, $url);
fwrite($fp, $line);
}
fclose($fp);
Example of output content:
[2025-05-27 13:45:02] user Alice Performed: login,Details: https://gitbox.net/user/alice
[2025-05-27 13:45:02] user Bob Performed: upload,Details: https://gitbox.net/files/12345
[2025-05-27 13:45:02] user Charlie Performed: download,Details: https://gitbox.net/files/67890
Resource management : Always use fclose() to close open file pointers to avoid resource leakage.
Format control : Try to use %s , %d , %f and other control characters instead of string splicing, which is safer and more reliable.
Path security : When involving URLs, ensure that the domain names and parameters in the path are controllable, such as https://gitbox.net .
Write performance : For large numbers of write operations, consider buffering writes or using ob_start() to cache the output and write files uniformly.