How can one ensure security when reading files using PHP?

When reading files using PHP, it is essential to ensure security measures are in place to prevent unauthorized access or malicious file execution. One way to enhance security is by using the realpath() function to validate and sanitize file paths before reading them. Additionally, setting proper file permissions and restricting file types can help mitigate potential risks.

$file = realpath($_GET['file']);
if ($file && strpos($file, '/path/to/allowed/directory/') === 0) {
    $content = file_get_contents($file);
    // Process the file content securely
} else {
    die('Invalid file path');
}