2

I've managed to login to a site via curl, but now I would like to redirect to a file to download. This file requires a login cookie to download. How would I go about redirecting and using my previously saved 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);
12shadow12
  • 307
  • 2
  • 10

1 Answers1

0

You've got CURLOPT_RETURNTRANSFER enabled, but you're not actually getting the value from 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;
Community
  • 1
  • 1
Jeff Puckett
  • 37,464
  • 17
  • 118
  • 167