In what scenarios would it be advisable to avoid linking directly to external documents from a PHP application for performance and security reasons?

Linking directly to external documents from a PHP application can introduce security vulnerabilities, such as allowing for remote code execution or exposing sensitive information. Additionally, linking to external documents can impact performance by increasing load times and potentially causing delays in rendering the page. To mitigate these risks, it is advisable to download the external document to the server before serving it to the user.

<?php

// URL of the external document
$externalDocumentUrl = 'https://example.com/external-document.pdf';

// Download the external document to the server
$localFilePath = '/path/to/save/external-document.pdf';
file_put_contents($localFilePath, file_get_contents($externalDocumentUrl));

// Serve the downloaded document to the user
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="external-document.pdf"');
readfile($localFilePath);

// Delete the downloaded document from the server
unlink($localFilePath);

?>