我看了不同看似相似的问题,但似乎无法理解它,也无法让它完全起作用。
情况:我有一个外部网站,我可以从那里下载数据和文件。为了下载这些,我首先需要登录。
我希望自动执行此过程,以便我只需点击一下即可登录和下载每日所需的某些数据文件。但是,我不知道如何在cURL中做到这一点,到目前为止还没有找到合适的解决方案。
这是我现在的代码:(这仅涵盖到目前为止的登录程序,我甚至不知道它是否登录。我只知道我可能会在存储cookie时看到它,但是在cookie.txt中没有。
<?php
$url = "http://www.example.com/login.jsp";
$postfields = "userId=abc&password=123";
$logon = curl_init($url);
curl_setopt($logon, CURLOPT_HEADER, 0);
curl_setopt($logon, CURLOPT_POSTFIELDS, $postfields);
curl_setopt($logon, CURLOPT_POST, 1);
curl_setopt($logon, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($logon, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($logon, CURLOPT_COOKIEFILE, "cookie.txt");
curl_setopt($logon, CURLOPT_POSTFIELDS, $postfields);
$result = curl_exec($logon);
curl_close($logon);
echo file_get_contents("cookie.txt");
这不返回任何内容,文件“cookie.txt”也不存在。我之前尝试使用以下方法创建一个文件,但是文件只是空的并且保持为空。
$fp = fopen("cookie.txt","w");
fclose($fp);
任何人都可以帮我提一些建议吗?
答案 0 :(得分:0)
cookie.txt
文件为空,因为您尚未使用任何Cookie数据填充它。
您最好的选择是替换
curl_setopt($logon, CURLOPT_COOKIEJAR, "cookie.txt");
curl_setopt($logon, CURLOPT_COOKIEFILE, "cookie.txt");
与
$cookiesString = '';
foreach ($_COOKIE as $name => $value) {
if (!empty($cookiesString)) {
$cookiesString .= ';';
}
$cookiesString .= $name . '=' . addslashes($value);
}
curl_setopt($ch, CURLOPT_COOKIE, $cookiesString);