PHP File Handling
PHP file handling enables you to perform operations to create, open, read from files, write to files and close them which makes it practical for logging operations and data storage along with content management without database usage.

File Handling Functions
Function | Description |
---|---|
fopen() | Opens a file or URL |
fread() | Reads from an open file |
fwrite() | Writes to an open file |
fclose() | Closes an open file |
File Modes for fopen()
Mode | Description |
---|---|
'r' | Read-only |
'w' | Write-only (truncates file) |
'a' | Write-only (appends to file) |
'r+' | Read/Write (file must exist) |
'w+' | Read/Write (truncates or creates) |
'a+' | Read/Write (creates if not exists) |
Example: Writing to a File
<?php $file = fopen("demo.txt", "w"); // Open for writing fwrite($file, "Hello, PHP File Handling!"); fclose($file); // Always close the file ?>
Example: Reading from a File
<?php $file = fopen("demo.txt", "r"); // Open for reading $content = fread($file, filesize("demo.txt")); // Read full file fclose($file); echo $content; // Output: Hello, PHP File Handling! ?>
Example : Append to a File
<?php $file = fopen("demo.txt", "a"); // Open for appending fwrite($file, "\nNew Line Added!"); fclose($file); ?>
Example : Error Handling
<?php $file = fopen("data.txt", "r") or die("Unable to open file!"); echo fread($file, filesize("data.txt")); fclose($file); ?>

- Always use fclose() to free resources
- Use file_exists() to check if a file is present
- Use is_writable() and is_readable() for safety
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.