我已经使用cURL成功连接,但我试图下载一个文件,但它不起作用。我知道这是cookie,因为当我打开下载的文件时,它包含一条授权的必需消息。不过,初始身份验证正在运行。有什么想法吗
// Create a curl handle to a non-existing location
$ch = curl_init('https://xxxx/');
// curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// ENABLE HTTP POST
curl_setopt ($ch, CURLOPT_POST, 1);
// SET POST PARAMETERS : FORM VALUES FOR EACH FIELD
curl_setopt ($ch, CURLOPT_POSTFIELDS, 'user=xxx&password=xxx');
// IMITATE CLASSIC BROWSER'S BEHAVIOUR : HANDLE COOKIES
curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
curl_setopt ($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
$fp = fopen("status.xml", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
curl_close($ch);
fclose($fp);
CURLOPT_COOKIEFILE
用于读取cookie,CURLOPT_COOKIEJAR
用于写入。
curl_setopt ($ch, CURLOPT_COOKIEJAR, '/path/to/cookie.txt');
确保您有cookie文件的完整路径,并且它有写入的权限
Cookies信息只需在句柄关闭后保存到文件中,就像手册中所说的那样:
CURLOPT_COOKIEJAR=>当句柄关闭时,例如在调用curl_close之后,要将所有内部cookie保存到的文件的名称。
手动:curl_setopt此外,您可能需要考虑这一点:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);