File Handling in PHP
? File Handling in PHP
File handling in PHP allows you to create, read, write, append, and delete files on the server. It's useful for storing user data, logs, reports, and more.
? Basic File Operations
1. Open a File – fopen()
$handle = fopen("file.txt", "r"); // r = read| Mode | Description |
|---|---|
r | Read only |
w | Write only (creates/truncates file) |
a | Append |
x | Create new, fails if file exists |
r+ | Read & write |
w+ | Read & write (truncates file) |
a+ | Read & append |
x+ | Read & write (new only) |
2. Write to a File – fwrite()
$file = fopen("example.txt", "w");fwrite($file, "Hello, world!");fclose($file);3. Read from a File – fread()
$file = fopen("example.txt", "r");$content = fread($file, filesize("example.txt"));fclose($file);echo $content;4. Read Line-by-Line – fgets()
$file = fopen("example.txt", "r");while (!feof($file)) { echo fgets($file) . "<br>";}fclose($file);5. Check if File Exists – file_exists()
if (file_exists("example.txt")) { echo "File exists!";} else { echo "File does not exist!";}6. Delete a File – unlink()
if (file_exists("old.txt")) { unlink("old.txt"); echo "File deleted.";}7. Quick Write – file_put_contents()
file_put_contents("data.txt", "This is quick content.");8. Quick Read – file_get_contents()
$data = file_get_contents("data.txt");echo $data;? Example: Simple Guestbook (Write & Read)
// write.php$name = $_POST['name'];file_put_contents("guests.txt", $name . "\n", FILE_APPEND);echo "Thanks, $name!";// read.php$guests = file("guests.txt");foreach ($guests as $guest) { echo htmlspecialchars($guest) . "<br>";}? Tips for File Handling
Always
fclose()your files.Use
file_exists()before reading or deleting.Use
htmlspecialchars()when displaying user input from a file.Be cautious with file permissions on the server.