How can PHP scripts be used to securely handle file access from external servers?

To securely handle file access from external servers in PHP scripts, it is important to validate and sanitize any user input, especially file paths, to prevent directory traversal attacks. Additionally, setting proper file permissions and using secure file handling functions can help mitigate risks associated with accessing files from external sources.

// Validate and sanitize user input for file path
$filePath = filter_input(INPUT_GET, 'file', FILTER_SANITIZE_STRING);

// Check if the file path is within a specific directory
$allowedDirectory = '/path/to/allowed/directory/';
if (strpos(realpath($filePath), $allowedDirectory) !== 0) {
    die('Access denied');
}

// Use secure file handling functions to access the file
$fileContents = file_get_contents($filePath);
// Process the file contents securely