What best practices should be followed when handling file operations in PHP to avoid segmentation faults?

Segmentation faults in PHP file operations can be avoided by properly checking for errors and closing file handles when they are no longer needed. It is important to handle errors gracefully using try-catch blocks and to always close file handles using fclose() after reading or writing to a file.

<?php
$filename = "example.txt";

// Open file for reading
$handle = fopen($filename, "r");

try {
    if ($handle === false) {
        throw new Exception("Unable to open file.");
    }

    // Read file contents
    $contents = fread($handle, filesize($filename));

    if ($contents === false) {
        throw new Exception("Unable to read file contents.");
    }

    // Close file handle
    fclose($handle);

    // Process file contents
    // ...

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

?>