About Lesson
File Functions – fopen()
, fwrite()
, fread()
, unlink()
These are the most commonly used file handling functions in PHP.
1. fopen()
– Open a File
Used to open a file for reading or writing.
Syntax:
fopen(filename, mode);
Common modes:
"r"
→ Read only"w"
→ Write (erase old content)"a"
→ Append (write at end of file)"r+"
→ Read & Write
Example:
PHP
<?php
$file = fopen("example.txt", "w"); // open file for writing
if ($file) {
echo "File opened successfully!";
fclose($file);
}
?>
2. fwrite()
– Write into File
Writes content into a file (must be opened in "w"
or "a"
mode).
Example:
PHP
<?php
$file = fopen("example.txt", "w");
fwrite($file, "Hello, this is a test file.\n");
fwrite($file, "We are learning PHP file handling.");
fclose($file);
echo "Data written successfully!";
?>
This will create example.txt
and store the text inside it.
3. fread()
– Read File Content
Reads data from an open file.
Syntax:
fread($file, filesize("filename"));
Example:
PHP
<?php
$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);
echo "File Content: <br>" . nl2br($content);
?>
It will display the file content in the browser.
4. unlink()
– Delete a File
Used to delete an existing file.
Example:
PHP
<?php
if (unlink("example.txt")) {
echo "File deleted successfully!";
} else {
echo "Error deleting file.";
}
?>