What are the best practices for file handling in PHP when reading and writing data?
When handling files in PHP, it is important to ensure proper error handling, close the file after use, and sanitize user inputs to prevent security vulnerabilities. Always check if the file exists before reading or writing to it, and use appropriate file modes for reading and writing operations.
// Example of reading data from a file
$filename = 'data.txt';
if (file_exists($filename)) {
$file = fopen($filename, 'r');
if ($file) {
while (($line = fgets($file)) !== false) {
echo $line;
}
fclose($file);
} else {
echo 'Unable to open file for reading.';
}
} else {
echo 'File does not exist.';
}