What are some best practices for beginners in PHP when working with file handling and output?

When working with file handling and output in PHP, beginners should ensure they are properly handling errors that may occur during file operations. It is important to check if a file exists before attempting to read from or write to it, and to close the file after finishing operations to free up system resources.

// Check if file exists before reading from it
$filename = "example.txt";
if (file_exists($filename)) {
    $file = fopen($filename, "r");
    // Read from file
    fclose($file);
} else {
    echo "File does not exist.";
}

// Check if file exists before writing to it
$filename = "example.txt";
if (file_exists($filename)) {
    $file = fopen($filename, "w");
    // Write to file
    fclose($file);
} else {
    echo "File does not exist.";
}