How can one ensure the integrity of transferred files when using PHP to copy them from a cloud service to a web server?

When transferring files from a cloud service to a web server using PHP, it is important to ensure the integrity of the transferred files by calculating and comparing checksums before and after the transfer. This can help detect any corruption or tampering that may have occurred during the transfer process.

// Calculate checksum of the original file
$original_checksum = md5_file('path_to_original_file');

// Copy the file from cloud service to web server
copy('path_to_cloud_file', 'path_to_web_server_file');

// Calculate checksum of the transferred file
$transferred_checksum = md5_file('path_to_web_server_file');

// Compare checksums to ensure file integrity
if($original_checksum === $transferred_checksum) {
    echo 'File transfer successful. Integrity preserved.';
} else {
    echo 'File transfer failed. Integrity compromised.';
}