如果有很多重定向,PHP curl的行为与命令行curl不同

tct7dpnv  于 2023-05-05  发布在  PHP
关注(0)|答案(2)|浏览(210)

这是我想下载的文件:

https://sourceforge.net/projects/minpspw/files/SDK%20%2B%20devpak/pspsdk%200.11.2/pspsdk-setup-0.11.2r3.exe

我可以像这样在命令行下载它(请替换):

curl --output pspsdk-setup-0.11.2r3.exe -L <URL>

有4个重定向,但最后保存了一个32.6MB的文件。现在我尝试在PHP中做同样的事情:

<?php 

$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://sourceforge.net/projects/minpspw/files/SDK%20%2B%20devpak/pspsdk%200.11.2/pspsdk-setup-0.11.2r3.exe");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_MAXREDIRS, 10);
curl_setopt($c, CURLOPT_AUTOREFERER, true);
curl_setopt($c, CURLOPT_COOKIEJAR, "cookie.jar");
curl_setopt($c, CURLOPT_USERAGENT, "curl/7.74.0"); // same as command line curl

file_put_contents("pspsdk-setup-0.11.2r3.exe", curl_exec($c));
curl_close($c);

但我只得到一个HTML着陆页说“您的下载将很快开始...”(着陆页被写入文件pspsdk-setup-0.11.2r3.exe)。
正如你在PHP中看到的,我只得到一个着陆页,而命令行curl下载实际的exe文件。
我尝试启用referer,cookie,我还将用户代理设置为与命令行curl相同。
如何修复我的PHP代码,使其下载的exe文件,而不仅仅是一个着陆页?

xcitsw88

xcitsw881#

我通过禁用referer header来实现这一点:

$c = curl_init();
curl_setopt($c, CURLOPT_URL, "https://sourceforge.net/projects/minpspw/files/SDK%20%2B%20devpak/pspsdk%200.11.2/pspsdk-setup-0.11.2r3.exe");
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_MAXREDIRS, 10);
curl_setopt($c, CURLOPT_USERAGENT, "curl/7.85.0");

file_put_contents("pspsdk-setup-0.11.2r3.exe", curl_exec($c));
curl_close($c);
agxfikkp

agxfikkp2#

您可以使用以下代码,它直接下载文件并存储在存储脚本的位置.

$url = "https://sourceforge.net/projects/minpspw/files/SDK%20%2B%20devpak/pspsdk%200.11.2/pspsdk-setup-0.11.2r3.exe";
$local_file = "pspsdk-setup-0.11.2r3.exe";

$fp = fopen($local_file, 'w');

$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($c, CURLOPT_FILE, $fp);

$data = curl_exec($c);

curl_close($c);
fclose($fp)

相关问题