问题:使用PHP中的CURL下载文件时出现问题。

huangapple go评论58阅读模式
英文:

Problem with download file via CURL in PHP

问题

我尝试使用curl PHP下载文件时遇到问题。

响应头:

问题:使用PHP中的CURL下载文件时出现问题。

PHP代码:

$filePath = $this->exchangePath . $this->exchangeFile;
$url = $this->exchangeURL;

$fp = fopen($filePath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);

下载后预览文件数据(106Kb):

问题:使用PHP中的CURL下载文件时出现问题。

服务器上的文件数据预览(1.9 Mb - 未来可能会更大,也许达到300Mb或更大):

问题:使用PHP中的CURL下载文件时出现问题。

请帮助我,谢谢。

英文:

I have a problem when i try download file with curl php.

Headers response

问题:使用PHP中的CURL下载文件时出现问题。

PHP Code

$filePath = $this->exchangePath . $this->exchangeFile;
$url = $this->exchangeURL;

$fp = fopen($filePath, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);

Preview file data after downloading (106Kb)

问题:使用PHP中的CURL下载文件时出现问题。

Preview file data on server (1.9 Mb - The file will be bigger in the future. Maybe 300Mb or large.)

问题:使用PHP中的CURL下载文件时出现问题。

Help me, please.

答案1

得分: 1

问题在于你忽略了Content-Encoding: gzip头部。服务器返回的数据是经过gzip编码的,而你没有解压它。

幸运的是,curl内置支持gzip解码(curl基本上一直支持gzip和deflate解码,但现代版本的curl还支持br和zstd)。

要启用支持的编码的自动解码,只需设置:

curl_setopt($ch, CURLOPT_ENCODING, '');

将CURLOPT_ENCODING设置为空字符串会打开所有支持的编码的自动解码。

此外,你应该使用二进制模式wb来打开文件,以防止Windows干扰你的\n字节。

英文:

the problem is that you're ignoring that Content-Encoding: gzip header. The server returns the data gzip-encoded, and you're not un-gzipping it.

Luckily for you, curl has built-in support for gzip decoding (curl has basically supported gzip and deflate decoding forever, but modern versions of curl also support br and zstd)

to enable automatic decoding of supported encodings, simply set

curl_setopt($ch,CURLOPT_ENCODING,'');
  • setting CURLOPT_ENCODING to emptystring turns on automatic decoding of all supported encodings.

aalso, you should use the fopen binary mode wb so Windows doesn't fuck with your \n bytes.

huangapple
  • 本文由 发表于 2023年2月24日 05:04:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550312.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定