2
我已經設法通過curl登錄到一個網站,但現在我想重定向到一個文件下載。該文件需要登錄cookie才能下載。我將如何去重定向和使用我以前保存的cookie?登錄成功後,我試圖設置下面的網址,但沒有奏效。登錄網站,並重定向到文件下載
<?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);