What are the potential security risks involved in downloading files from a remote server using PHP?

When downloading files from a remote server using PHP, potential security risks include exposing sensitive information, executing malicious code, and downloading harmful files. To mitigate these risks, it is important to validate user input, sanitize file names, and restrict file types to be downloaded.

// Validate user input and sanitize file name
$remoteFile = filter_var($_GET['file'], FILTER_SANITIZE_STRING);

// Restrict file types to be downloaded
$allowedTypes = ['pdf', 'doc', 'txt'];
$extension = pathinfo($remoteFile, PATHINFO_EXTENSION);

if (in_array($extension, $allowedTypes)) {
    // Download file from remote server
    $file = file_get_contents('http://example.com/' . $remoteFile);
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($remoteFile) . '"');
    echo $file;
} else {
    echo 'Invalid file type.';
}