How to Read and Write from Files in PHP ?
Last Updated :
13 Feb, 2024
In PHP, reading from and writing to files is a common task in web development, especially for tasks such as reading configuration files, processing data files, or logging information. PHP provides built-in functions for handling file operations, making it straightforward to perform file read and write operations.
Reading from a File:
Writing to a File:
- Use
fopen()
with mode 'w'
or 'a'
to open a file pointer for writing.
- Use
fwrite()
to write data to the file.
- Close the file pointer using
fclose()
when done.
Example (Reading from a File):
// Open a file for reading
$handle = fopen("file.txt", "r");
// Read data from the file
while (($line = fgets($handle)) !== false) {
echo $line;
}
// Close the file handle
fclose($handle);
Example (Writing to a File):
// Open a file for writing (create if not exists, truncate if exists)
$handle = fopen("file.txt", "w");
// Write data to the file
fwrite($handle, "Hello, World!\n");
// Close the file handle
fclose($handle);
Important Points:
- Ensure proper permissions are set on the file and directory to allow read and write operations.
- Handle errors and exceptions appropriately when performing file operations to ensure robustness.
Share your thoughts in the comments
Please Login to comment...