PHP CURL模拟POST请求及文件下载处理
以下代码利用curl模拟了post请求链接,但执行后直接在页面显示了文件内容。如何调整代码,使其不显示内容而是直接下载请求到的.torrent格式文件?
function curl_post($header,$data,$url)
{
$ch = curl_init();
$res= curl_setopt ($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt ($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_HTTPHEADER,$header);
$result = curl_exec ($ch);
curl_close($ch);
if ($result == NULL) {
return 0;
}
return $result;
}
$url = 'http://www.bttiantang.com/download4.php' ;
$header = array("Host:www.bttiantang.com",
"Content-Type:application/x-www-form-urlencoded",
'User-Agent: Mozilla/4.0 (compatible; MSIE .0; Windows NT 6.1; Trident/4.0; SLCC2;)');
$data = 'action=download&id=26881&uhash=eecf3d3071a7b672c314bc39';
$ret = curl_post($header, $data,$url);
//需将内容显示修改为文件下载
echo $ret;
------解决思路----------------------
首先,移除代码中的 echo $ret; 语句,避免直接将内容输出到屏幕。
接着,将变量 $ret 中获取的数据写入文件进行保存。
------解决思路----------------------
$ret = curl_post($header, $data,$url);
//需将内容显示修改为文件下载
$filename = 'x.torrent';
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=$filename");
echo $ret;
生成的 x.torrent 文件可以使用迅雷打开验证。

本文分享了关于修改PHP curl模拟post请求内容后并下载文件的解决思路,希望大家喜欢,请持续关注本站,本站每天都有新的内容更新,谢谢。!