Writing files lets your program save information on the computer. This helps keep data even after the program stops.
0
0
Writing files (fwrite, file_put_contents) in PHP
Introduction
Saving user input like notes or settings to a file.
Creating a log file to record events or errors.
Storing data from a form submission for later use.
Generating reports or text files automatically.
Syntax
PHP
<?php // Using fwrite $file = fopen('filename.txt', 'w'); fwrite($file, 'Your text here'); fclose($file); // Using file_put_contents file_put_contents('filename.txt', 'Your text here'); ?>
fwrite needs you to open and close the file manually.
file_put_contents is simpler and does all steps in one function.
Examples
This writes 'Hello World!' to example.txt using fopen and fwrite.
PHP
<?php $file = fopen('example.txt', 'w'); fwrite($file, 'Hello World!'); fclose($file); ?>
This does the same as above but in one line with file_put_contents.
PHP
<?php file_put_contents('example.txt', 'Hello World!'); ?>
This writes two lines to the file using newline characters.
PHP
<?php file_put_contents('example.txt', "Line 1\nLine 2\n"); ?>
Sample Program
This program writes a greeting message to 'greeting.txt' using fwrite, then reads and prints it.
PHP
<?php // Write a greeting to a file using fwrite $filename = 'greeting.txt'; $file = fopen($filename, 'w'); fwrite($file, "Hello, friend!\nWelcome to PHP file writing."); fclose($file); // Read and print the file content $content = file_get_contents($filename); echo $content; ?>
OutputSuccess
Important Notes
Always close files opened with fopen using fclose to save changes properly.
file_put_contents will overwrite the file by default. Use FILE_APPEND flag to add instead.
Make sure your script has permission to write to the folder where the file is saved.
Summary
Use fwrite when you want more control opening and closing files.
Use file_put_contents for quick and simple file writing.
Writing files helps save data permanently outside your program.