How can a PHP script handle failed downloads and ensure the process is successful?
When handling failed downloads in PHP, you can use error handling techniques to catch any errors that occur during the download process. One approach is to use try-catch blocks to detect exceptions and handle them accordingly. Additionally, you can check the HTTP response status code to determine if the download was successful or not.
<?php
$url = 'http://example.com/file-to-download.zip';
$destination = 'downloaded-file.zip';
$ch = curl_init($url);
$fp = fopen($destination, 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
try {
curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode != 200) {
throw new Exception('Failed to download file');
}
echo 'Download successful!';
} catch (Exception $e) {
echo 'Error downloading file: ' . $e->getMessage();
}
fclose($fp);
curl_close($ch);
?>