PHP File Handling – Read, Write, Create, and Delete Files

PHP provides built-in functions to manage files on the server. You can use fopen(), fread(), fwrite(), and fclose() to open, read, write, and close files. Use file_exists() to check if a file is present and unlink() to delete it. PHP can also create new files automatically when writing if the file doesn’t exist. File handling is useful for logs, user data storage, and more.

1. Open a File

read-file.php


$file = fopen("example.txt", "r"); // Modes: r, w, a, r+, etc.
  • "r" = read
  • "w" = write (overwrite)
  • "a" = append
  • "r+" = read/write

 

2. Read a File

read-file.php


$file = fopen("example.txt", "r");
$content = fread($file, filesize("example.txt"));
fclose($file);

echo $content;

3. Write to a File

write-file.php


$file = fopen("example.txt", "w");
fwrite($file, "Hello, this is a test.");
fclose($file);

If example.txt doesn’t exist, PHP will create it.

4. Append Data to a File

append-file.php


$file = fopen("example.txt", "a");
fwrite($file, "\nNew appended line.");
fclose($file);

5. Delete a File

delete-file.php


if (file_exists("example.txt")) {
    unlink("example.txt");
    echo "File deleted.";
} else {
    echo "File not found.";
}

6. Check If File Exists

check-file.php


if (file_exists("example.txt")) {
    echo "File exists.";
} else {
    echo "File does not exist.";
}

Summary Table

Task PHP Function
Open file fopen()
Read file fread() / file_get_contents()
Write file fwrite()
Close file fclose()
Delete file unlink()
File check file_exists()