fopen()
in PHP
fopen()
is used to open a file or a URL in PHP. It prepares the file so you can read from it, write to it, or both, depending on the mode you choose.
Syntax:
fopen(filename, mode, include_path, context)
Parameter | Description |
---|---|
filename |
Required. The path to the file or URL. |
mode |
Required. Specifies what you want to do with the file. |
include_path |
Optional. Search for the file in the include_path too. |
context |
Optional. A context stream resource. |
Common File Modes:
Mode | Purpose |
---|---|
r |
Open for reading only. File must exist. |
w |
Open for writing only. Erases the file or creates new. |
a |
Open for writing only. Places pointer at end; creates if not exists. |
x |
Create and open for writing only. If file exists, fopen() fails. |
r+ |
Open for reading and writing. File must exist. |
w+ |
Open for reading and writing. Erases file or creates new. |
a+ |
Open for reading and writing. Pointer at end; creates if not exists. |
Basic Examples:
1. Open a file for reading
<?php
$file = fopen("example.txt", "r");
if ($file) {
echo "File opened successfully.";
fclose($file);
} else {
echo "Unable to open file.";
}
?>
Here,
example.txt
must already exist. Otherwise,fopen()
returns false.
2. Open a file for writing (and overwrite contents)
<?php
$file = fopen("newfile.txt", "w");
if ($file) {
fwrite($file, "Hello, World!");
fclose($file);
echo "File written successfully.";
} else {
echo "Unable to open file.";
}
?>
If
newfile.txt
exists, it will be cleared first.
If it doesn’t exist, PHP will create it.
3. Open a file for appending (writing at the end)
<?php
$file = fopen("log.txt", "a");
if ($file) {
fwrite($file, "New log entry at " . date("Y-m-d H:i:s") . "\n");
fclose($file);
echo "Log updated.";
} else {
echo "Unable to open log file.";
}
?>
Appending is good for logs because new data is added at the end without deleting the old data.
4. Trying to open a file that doesn’t exist (reading mode)
<?php
$file = fopen("nonexistent.txt", "r");
if ($file) {
echo "File opened.";
fclose($file);
} else {
echo "File does not exist!";
}
?>
Since we are using
r
, the file must exist, otherwise we get false.
Important:
- Always use
fclose($file);
after finishing with a file to free up resources. - Always check if
fopen()
was successful before doing anything. - You can use
feof()
,fgets()
,fwrite()
, and other file functions after usingfopen()
.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.