简体   繁体   English

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

[英]Login to site and redirect to file download

I've managed to login to a site via curl, but now I would like to redirect to a file to download. 我已经设法通过curl登录到一个站点,但是现在我想重定向到一个文件进行下载。 This file requires a login cookie to download. 此文件需要登录cookie才能下载。 How would I go about redirecting and using my previously saved cookie? 我将如何重定向和使用以前保存的Cookie? I tried to set the url below after the login was successful but that didn't work. 登录成功后,我尝试在下面设置网址,但这没有用。

<?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);

You've got CURLOPT_RETURNTRANSFER enabled, but you're not actually getting the value from curl_exec 您已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);

So you should assign that to a value, set the header appropriately , and then print the response. 因此,您应该将其分配给一个值, 适当设置标题 ,然后打印响应。

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

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

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