What are some best practices for utilizing PHP modes effectively in functions like fopen()?

When using functions like fopen() in PHP, it is important to utilize the appropriate modes effectively to ensure proper file handling. Some best practices include using 'r' for reading, 'w' for writing (and truncating the file), 'a' for appending, and 'b' for binary mode. It is also important to handle errors and exceptions when working with file operations.

// Example of utilizing PHP modes effectively in fopen()

$file = 'example.txt';

// Open file for reading
$handle = fopen($file, 'r');
if ($handle) {
    // Read file contents
    $contents = fread($handle, filesize($file));
    
    // Close file handle
    fclose($handle);
    
    // Output file contents
    echo $contents;
} else {
    echo 'Error opening file';
}