What are best practices for reading and writing files in PHP?

Best practices for reading and writing files in PHP include using the appropriate file handling functions, checking for errors, and properly closing files after use to free up resources. It is also important to sanitize user input to prevent security vulnerabilities.

// Example of reading a file in PHP
$filename = "example.txt";
$file = fopen($filename, "r") or die("Unable to open file!");
$content = fread($file, filesize($filename));
fclose($file);

// Example of writing to a file in PHP
$filename = "example.txt";
$file = fopen($filename, "w") or die("Unable to open file!");
$content = "Hello, world!";
fwrite($file, $content);
fclose($file);