-
Hajipur, Bihar, 844101
Creating and writing files is a fundamental part of PHP web development. Whether you want to store user feedback, generate reports, or save logs, PHP provides simple and powerful functions to create files and write data into them.
This tutorial explains how to create files, write content, append data, and handle errors securely. By the end, you’ll be able to manage file creation and writing efficiently.
When Vrinda builds a simple diary application, she needs to save each entry in a file. Similarly, Ananya wants to log website visits in a file to track user activity. Writing files allows you to persist data across sessions, making your applications dynamic and interactive.
With PHP, you can:
Create new files if they don’t exist
Write content to files
Append data without overwriting existing content
Handle errors if the file cannot be created or written to
The fopen()
function can be used to create a file if it doesn’t exist. Use the "w"
mode to create a new file or overwrite an existing one.
<?php
$file = fopen("diary.txt", "w"); // create or overwrite file
if ($file) {
echo "File created successfully!";
} else {
echo "Failed to create file.";
}
?>
"w"
mode will overwrite the file if it already exists.
"x"
mode can also create a file, but it will throw an error if the file already exists.
To write data into a file, use fwrite()
after opening the file.
<?php
$file = fopen("diary.txt", "w");
fwrite($file, "Today Vrinda learned PHP file creation.\n");
fclose($file);
echo "Data written successfully!";
?>
Always close the file using fclose()
after writing.
Adding \n
inserts a new line in the file.
This code will create diary.txt
and write a single line mentioning Vrinda’s activity.
If you want to add new data without deleting old content, open the file in append mode "a"
.
<?php
$file = fopen("diary.txt", "a");
fwrite($file, "Ananya added a new entry today.\n");
fclose($file);
echo "New entry appended!";
?>
"a"
mode places the cursor at the end of the file.
New content is added after existing lines, keeping the previous data intact.
This is useful when multiple users submit feedback or updates, like Vrinda and Ananya adding diary entries.
You can write multiple lines at once by using fwrite()
repeatedly or by including \n
within a single string.
<?php
$file = fopen("diary.txt", "a");
$data = "Riya learned about file writing today.\nShe plans to practice more.\n";
fwrite($file, $data);
fclose($file);
?>
This writes two lines into the file in a single operation, keeping the content organized.
PHP also provides file_put_contents()
for simpler file writing. It automatically opens, writes, and closes the file.
<?php
$data = "Vrinda started her PHP project.\n";
file_put_contents("diary.txt", $data, FILE_APPEND); // append mode
echo "Data written using file_put_contents!";
?>
Adding the FILE_APPEND
flag ensures data is added to the end instead of overwriting.
Without FILE_APPEND
, the file will be overwritten.
When creating or writing files, always handle errors to prevent crashes.
<?php
$file = @fopen("log.txt", "w") or die("Cannot open file!");
fwrite($file, "Ananya visited the page.\n");
fclose($file);
?>
@
suppresses warnings
die()
displays a custom message if the file cannot be opened
This ensures your application handles failures securely and user-friendly.
Suppose Riya creates a feedback form. Each submission should be saved to feedback.txt
.
<?php
$name = $_POST['name'];
$feedback = $_POST['feedback'];
$file = fopen("feedback.txt", "a");
fwrite($file, "Name: $name\nFeedback: $feedback\n\n");
fclose($file);
echo "Thank you, $name! Your feedback has been saved.";
?>
Every new submission is appended without deleting previous feedback.
Each entry is separated by a blank line for clarity.
If Vrinda wants to track website visits:
<?php
date_default_timezone_set("Asia/Kolkata");
$log = "User visited on " . date("Y-m-d H:i:s") . "\n";
file_put_contents("visits.log", $log, FILE_APPEND);
echo "Visit logged!";
?>
Each visit is recorded with a timestamp.
FILE_APPEND
ensures previous logs are preserved.
Always close files using fclose()
to free server resources.
Use append mode when multiple users or actions need to add content.
Check if files exist before writing to prevent accidental overwrites.
Validate user input if data comes from forms to prevent security issues.
Use proper file permissions to prevent unauthorized access.
PHP makes file creation and writing straightforward and efficient. You can:
Create new files with fopen()
in "w"
or "x"
mode
Write data using fwrite()
Append new content with "a"
mode or FILE_APPEND
flag in file_put_contents()
Handle errors safely using @fopen()
and die()
Using these methods, Vrinda, Ananya, and Riya can build features like diaries, logs, and feedback systems, keeping data persistent and organized.
Create a file named diary.txt
and write the text “Today Vrinda learned PHP file creation.” into it.
Append a new line “Ananya added a diary entry today.” to diary.txt
without deleting existing content.
Use file_put_contents()
to write “Riya started a new project.” into project.txt
and append it.
Write multiple lines at once into notes.txt
using fwrite()
and \n
for line breaks.
Check if log.txt
exists before creating it and display a message if it does.
Handle errors when opening a file that may not exist using @fopen()
and die()
.
Create a feedback system where user name and comments are appended to feedback.txt
.
Log the current date and time into visits.log
each time the page is accessed.
Overwrite the content of summary.txt
with a new line using "w"
mode.
Open a file, write data into it, and then close it using fclose()
to release resources.