登录网站并重定向到文件下载

时间:2016-11-18 23:21:10

标签: php curl

我已成功通过curl登录网站,但现在我想重定向到要下载的文件。此文件需要登录cookie才能下载。我将如何重定向并使用以前保存的cookie?我尝试在登录成功后设置下面的URL但是没有用。

<?php
$username = "user";
$password = "pass";
$url = "https://www.example.com/login";
$urldl = "https://www.example.com/get-download/abc.xyz";
$cookie = "cookie.txt";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);

if (curl_errno($ch)) die(curl_error($ch));

$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($response);
$token = $doc->getElementById("csrf_token")->attributes->getNamedItem("value")->value;
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_setopt($ch, CURLOPT_POST, true);
$params = array(
    'username' => $username,
    'password' => $password,
    'csrf_token' => $token
);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_exec($ch);

if (curl_errno($ch)) print curl_error($ch);


curl_setopt($ch, CURLOPT_URL, $urldl);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);


curl_close($ch);

1 个答案:

答案 0 :(得分:0)

您已启用CURLOPT_RETURNTRANSFER,但实际上并未从curl_exec

获取值
// I want the result returned from exec
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// but I'm not gonna do anything with it...
curl_exec($ch);

因此,您应该将其分配给值set the header appropriately,然后打印响应。

$result = curl_exec($ch);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="foo.bar"');
echo $result;
相关问题