Are there any best practices for handling file operations in PHP to prevent unintended consequences like opening files in the wrong format?

When handling file operations in PHP, it is important to always validate the file format before opening it to prevent unintended consequences. One way to do this is by checking the file extension or using functions like `finfo_file()` to determine the file type before proceeding with any file operations.

$file = 'example.txt';

// Check file extension before opening
$allowed_extensions = ['txt', 'csv', 'pdf'];
$extension = pathinfo($file, PATHINFO_EXTENSION);

if (!in_array($extension, $allowed_extensions)) {
    die('Invalid file format');
}

// Open file for reading
$handle = fopen($file, 'r');
if ($handle) {
    // File operations
    fclose($handle);
} else {
    die('Error opening file');
}