About Lesson
Reading and writing files
Writing to a File:
fopen()
→ Opens a file.fwrite()
→ Writes data into the file.fclose()
→ Closes the file.
Example:
PHP
<?php
// Open file in write mode ("w") - if file doesn’t exist, it will create one
$file = fopen("example.txt", "w");
// Write some content
fwrite($file, "Hello, this is my first file handling example in PHP!");
// Close the file
fclose($file);
echo "Data written to file successfully!";
?>
Output:
After running, a file example.txt will be created with your text inside.
2. Reading from a File:
fopen()
→ Opens file.fread()
→ Reads file content.filesize()
→ Gets file size (to read full file).fclose()
→ Close the file.
Example:
PHP
<?php
// Open file in read mode ("r")
$file = fopen("example.txt", "r");
// Read content (need file size)
$content = fread($file, filesize("example.txt"));
// Close the file
fclose($file);
echo "File Content: " . $content;
?>
Output:
File Content: Hello, this is my first file handling example in PHP!
Modes in fopen()
:
"r"
→ Read only (file must exist)."w"
→ Write only (creates new file, erases old content)."a"
→ Append (write from end of file, keeps old content)."r+"
→ Read and write."w+"
→ Read and write (overwrites file)."a+"
→ Read and write (append mode).