PHP File Handling

PHP File Handling Tutorial
PHP File Handling provides functions to create, open, read, write, append, and delete files. File handling is useful for storing data, logs, user input, or configuration without using a database.
Opening a File (fopen)
Modes in fopen()
| Mode | Description |
|---|---|
r | Read only (file must exist) |
w | Write only (creates file or truncates existing file) |
a | Append only (creates file if not exists) |
r+ | Read and write (file must exist) |
w+ | Read and write (creates or truncates file) |
a+ | Read and append (creates file if not exists) |
Writing to a File (fwrite)
w mode overwrites existing content.
Appending to a File (a Mode)
Reading a File (fread)
Reading a File Line by Line (fgets)
Reading a File into an Array (file())
Deleting a File (unlink)
Checking if a File Exists (file_exists)
File Upload Example
HTML Form:
PHP Script (upload.php):
Summary
Use
fopen(),fread(),fwrite(),fclose()for basic file operations.amode appends data;wmode overwrites.file()reads file into array;fgets()reads line by line.Always check with
file_exists()before reading or deleting.unlink()deletes a file.File upload requires
enctype="multipart/form-data"in the form.
