What are the best practices for handling file downloads from external servers using CURL in PHP to ensure data integrity and security?

When downloading files from external servers using CURL in PHP, it is important to ensure data integrity and security by verifying the file's checksum and using secure connections. One way to achieve this is by calculating the checksum of the downloaded file and comparing it with the expected checksum provided by the server. Additionally, always use HTTPS connections to prevent man-in-the-middle attacks.

// Initialize CURL session
$ch = curl_init();

// Set URL to download file from
$url = 'https://example.com/file.zip';
curl_setopt($ch, CURLOPT_URL, $url);

// Set options for secure connection
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);

// Execute CURL session
$response = curl_exec($ch);

// Calculate checksum of downloaded file
$downloaded_checksum = md5($response);

// Verify checksum with expected checksum provided by server
$expected_checksum = 'abcdef1234567890';
if ($downloaded_checksum === $expected_checksum) {
    // Save the downloaded file
    file_put_contents('downloaded_file.zip', $response);
    echo 'File downloaded successfully and checksum matched.';
} else {
    echo 'Checksum mismatch. File may be corrupted or tampered with.';
}

// Close CURL session
curl_close($ch);