What are some potential pitfalls to consider when saving and reading data from a text file in PHP?
One potential pitfall is not handling errors properly when saving or reading data from a text file. It's important to check for file permissions, file existence, and handle any potential exceptions that may occur during file operations.
// Save data to a text file with error handling
$file = 'data.txt';
$data = 'Hello, world!';
if (file_put_contents($file, $data) === false) {
echo "Error saving data to file.";
} else {
echo "Data saved successfully.";
}
```
```php
// Read data from a text file with error handling
$file = 'data.txt';
if (!file_exists($file) || !is_readable($file)) {
echo "File does not exist or is not readable.";
} else {
$data = file_get_contents($file);
echo "Data read successfully: " . $data;
}