PHP File Handling
PHP can read from and write to files on the server using functions like fopen(), fread(), fwrite(), and fclose(). This is useful for logging, storing simple data, or generating reports without a database.
Always open files with the correct mode (like "r" for read, "w" for write, or "a" for append) and close them with fclose() when finished to free system resources.
$fh = fopen("file.txt", "r");
fwrite($fh, "text");
fclose($fh);Reading files
fopen($file, "r") opens a file for reading, fread() reads its content, and file_get_contents() offers a simpler one-line way to read an entire file into a string.
Writing files
fopen($file, "w") opens (and creates if needed) a file for writing, overwriting existing content, while "a" mode appends to the end instead.
<?php
file_put_contents("notes.txt", "Hello File!");
echo file_get_contents("notes.txt");
?>Hello File!file_put_contents() writes text to a file, and file_get_contents() reads it back.
<?php
$fh = fopen("log.txt", "a");
fwrite($fh, "New entry\n");
fclose($fh);
echo "Logged!";
?>Logged!Opening in append ("a") mode adds new content to the end of the file without erasing it.
Key points
- fopen() opens a file, and fclose() closes it when done.
- file_get_contents() and file_put_contents() offer simple one-line read/write operations.
- Mode "r" reads, "w" overwrites, and "a" appends to a file.
- Always close files to release system resources.
