What are the best practices for securely handling file operations in PHP to prevent unauthorized access to server files?

To securely handle file operations in PHP and prevent unauthorized access to server files, it is important to properly validate user input, sanitize file paths, and restrict access to sensitive files. One way to achieve this is by using PHP's built-in functions like realpath() to resolve file paths and ensure they point to the correct location on the server.

<?php
$filename = '/path/to/file.txt';

// Validate and sanitize the file path
$realpath = realpath($filename);

if ($realpath && strpos($realpath, '/path/to/') === 0) {
    // Proceed with file operations
    // For example, read the file contents
    $contents = file_get_contents($realpath);
    echo $contents;
} else {
    // Handle unauthorized access
    echo 'Unauthorized access';
}
?>