我正试图找到一种方法来阻止活跃的PHP Curl下载。我从远程服务器下载大文件,有时我想在启动后取消下载。我已尝试在CURLOPT_PROGRESSFUNCTION
内返回false,但这不起作用。我也尝试删除正在下载的文件,但也没有用(web stats显示下载仍在继续)。
以下代码通过快速ajax调用触发:
$ch = curl_init( $file->url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOPROGRESS, false );
curl_setopt($ch, CURLOPT_FILE, $targetFile); //save the file to here
curl_setopt( $ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) use ($download_id) {
if ( $download_size == 0 ) {
$progress = 0;
} else {
$progress = round( $downloaded_size * 100 / $download_size );
}
// if download complete trigger completed function
if($progress == 100) {
self::DownloadCompleted($download_id);
}
});
$curl = curl_exec($ch);
答案 0 :(得分:0)
解决方案是在CURLOPT_PROGRESSFUNCTION
函数中返回一个非零值,根据评论中的drew010。
为了完成这项工作,我在函数中添加了一个检查以查看文件是否存在,如果该函数返回1并且中止。我想在取消下载时在目录中创建一个与下载ID同名的文件。它适用于我。
$ch = curl_init( $file->url );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOPROGRESS, false );
curl_setopt($ch, CURLOPT_FILE, $targetFile); //save the file to here
curl_setopt( $ch, CURLOPT_PROGRESSFUNCTION, function($resource, $download_size, $downloaded_size, $upload_size, $uploaded_size) use ($download_id) {
//if the file exists, the download is aborted
if(file_exists('path/to/directory/cancel.'.$download_id)) {
Self::CleanupCancelledDownload; //function to clean up the partially downloaded file, etc.
return 1; //returning a non-zero value cancels the CURL download.
}
});
$curl = curl_exec($ch);