What are the recommended best practices for handling file transfers in PHP, especially when dealing with external sources?

When handling file transfers in PHP, especially when dealing with external sources, it is recommended to use secure protocols like HTTPS, validate user input to prevent directory traversal attacks, and sanitize file names to avoid potential security vulnerabilities.

// Example of handling file transfer securely in PHP
$fileUrl = 'https://example.com/file.txt';
$localFilePath = '/path/to/save/file.txt';

if (filter_var($fileUrl, FILTER_VALIDATE_URL)) {
    $fileData = file_get_contents($fileUrl);
    
    if ($fileData !== false) {
        file_put_contents($localFilePath, $fileData);
        echo 'File downloaded successfully.';
    } else {
        echo 'Error downloading file.';
    }
} else {
    echo 'Invalid file URL.';
}