Course Content
About Lesson

File Functions – fopen(), fwrite(), fread(), unlink()

These are the most commonly used file handling functions in PHP.

Used to open a file for reading or writing.

fopen(filename, mode);
  • "r" → Read only
  • "w" → Write (erase old content)
  • "a" → Append (write at end of file)
  • "r+" → Read & Write
PHP
<?php
$file = fopen("example.txt", "w");  // open file for writing
if ($file) {
    echo "File opened successfully!";
    fclose($file);
}
?>

Writes content into a file (must be opened in "w" or "a" mode).

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.

Reads data from an open file.

fread($file, filesize("filename"));
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.

Used to delete an existing file.

PHP
<?php
if (unlink("example.txt")) {
    echo "File deleted successfully!";
} else {
    echo "Error deleting file.";
}
?>