PHP provides a set of built-in functions for file handling that allow you to create, open, read, write, and close files on the server. Here's a quick overview with examples:
Common File Handling Functions in PHP
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_exists() |
Checks whether a file exists |
filesize() |
Gets the size of a file |
unlink() |
Deletes a file |
file_get_contents() |
Reads entire file into a string |
file_put_contents() |
Writes a string to a file |
File Open Modes (Used inĀ fopen()
)
Mode |
Description |
'r' |
Read only |
'w' |
Write only, erases contents |
'a' |
Write only, appends to file |
'x' |
Write only, creates new file |
'r+' |
Read/Write, pointer at beginning |
'a+' |
Read/Write, pointer at end |
Example: Creating and Writing to a File
Example: Reading from a File
Example: Reading/Writing the Whole File at Once