使用 Curl 下载大文件而不造成内存过载
使用 cURL 下载大型远程文件时,将整个文件读入内存的默认行为可能会出现问题,尤其是对于大量数据。为了应对这一挑战,请考虑以下优化方法:
我们可以使用以下修改后的代码将下载的文件直接流式传输到磁盘,而不是将下载的文件读入内存:
<?php set_time_limit(0); // Specify the destination file to save the download $fp = fopen(dirname(__FILE__) . '/localfile.tmp', 'w+'); // Replace spaces in the URL with %20 for proper handling $ch = curl_init(str_replace(" ", "%20", $url)); // Set a high timeout value to prevent interruptions while downloading large files curl_setopt($ch, CURLOPT_TIMEOUT, 600); // Stream curl response to disk curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Execute the download and close all resources curl_exec($ch); curl_close($ch); fclose($fp); ?>
此代码snippet 初始化 cURL,设置适当的超时,并将其配置为将响应直接写入指定文件,而不是将其加载到内存中。通过将下载流式传输到磁盘,您可以在处理大文件时显着减少内存使用量。
以上是如何使用curl下载大文件而不造成内存过载?的详细内容。更多信息请关注PHP中文网其他相关文章!