Why Work with the File System?
You can:
-
Store data without a database
-
Handle uploads
-
Manage logs, configuration files, or user-generated content
️ Common File Operations in PHP
1. Opening a File
| Mode | Description |
|---|---|
r |
Read-only |
w |
Write (truncates file) |
a |
Append |
x |
Create new, fail if exists |
r+ |
Read/write |
2. Reading a File
3. Writing to a File
Or appending:
4. Reading the Entire File at Once
5. Writing a Whole File
Directory Operations
✅ Create a Directory
✅ Check if File/Folder Exists
✅ Delete a File or Directory
File Upload Example
HTML Form:
PHP (upload.php):
Best Practices
-
Always check
file_exists()before reading or writing. -
Use
fclose()to release system resources. -
Use
htmlspecialchars()when displaying file content in the browser. -
Validate and sanitize file uploads to prevent security risks.
