What are the potential pitfalls of using readfile and filesize functions from a different domain in PHP?

When using readfile and filesize functions from a different domain in PHP, potential pitfalls include security risks such as exposing sensitive information or executing malicious code. To mitigate these risks, it is important to validate and sanitize input data, and ensure that the file being accessed is within a safe directory.

// Example code snippet to safely use readfile and filesize functions from a different domain
$allowed_directories = ['/path/to/safe/directory/'];

$requested_file = $_GET['file'];

foreach ($allowed_directories as $directory) {
    if (strpos($requested_file, $directory) === 0) {
        $file_path = $requested_file;
        break;
    }
}

if (isset($file_path) && file_exists($file_path)) {
    $file_size = filesize($file_path);
    header('Content-Type: application/octet-stream');
    header('Content-Length: ' . $file_size);
    readfile($file_path);
} else {
    echo "File not found or access denied.";
}