简体   繁体   English

如何确保使用cURL保存文件

[英]How to make sure file saved by using cURL

<?php
$source = 'http://www.xxx.com/1.jpg';
$fileBody = date('YmdHis') . rand(1000, 9999);
$extension = pathinfo($source, PATHINFO_EXTENSION);
$fileName = $fileBody . '.' . $extension;

$ch = curl_init($source);
$fp = fopen($path . $fileName, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
clearstatcache();

return $fileName;

This is how I grab image from internet, the image saved successfully and I will return file name for ajax to make immediately thumbnail, but sometimes php return the $fileName when it still processing download, therefore JavaScript reveal empty image on the page, how response after the file indeed been download. 这是我从互联网上抓取图像的方法,图像成功保存,我将返回ajax的文件名以立即制作缩略图,但有时php在仍在处理下载时返回$ fileName,因此JavaScript在页面上显示空图像,如何响应文件确实被下载后。

curl_exec returns true on success and false on failure. curl_exec成功返回true ,失败返回false Use that information. 使用该信息。

Also, You can check curl_getinfo to make sure the transfer completed successfully and was not empty. 另外,您可以检查curl_getinfo以确保传输成功完成并且不为空。 (You get http_code there for example, as well as content_type and size_download ). (你得到http_code有例如,以及content_typesize_download )。

$downComplete = false;
while(!$downComplete)
{
   if(!file_exist($filePath))
    {
        sleep(1);
    }
    else
    {
     $downComplete = true; 
     break;
    }
}

Hi,Above is an idea for check if file is completely downloaded,i think it's useful, main idea is check saved file all the time until its finished download,then you can display the img to front end..you can add it after your curl code,i didn't run it myself,so just an idea.. 嗨,以上是一个检查文件是否已完全下载的想法,我认为这很有用,主要思想是一直检查保存的文件,直到完成下载为止,然后您可以将img显示在前端。卷曲代码,我自己没有运行它,所以只是一个想法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM