您同时设置了两次CURLOPT_COOKIEJAR
,CURLOPT_COOKIEFILE
最终结果将是不同的值。'/cookie.txt'
将文件存储在系统根目录中,并将dirname(__FILE__) . '/cookie.txt'
文件存储在与当前正在执行的脚本相同的目录中。确保您只设置每个选项一次,具有相同的值(可能是后者)。
您还使用相同的句柄发出两个请求 - 这不是推荐的方法,并且可能在语义上不正确,因为您最终将 POST 到两个页面,而第二个页面可能应该是 GET。
我建议将 cookie jar 路径存储在块顶部的变量中,然后将其传入。这样可以更容易地查看发生了什么。
我怀疑你想要更像这样的东西:
<?php
// Username and password for login
$username = 'USERNAME';
$password = 'PASSWORD';
// Create the target URLs
// Don't forget to escape your user input!
$loginUrl = "http://www.forum.net/member.php?action=do_login";
$reputationUrl = "http://www.forum.net/reputation.php?uid=" . urlencode($_GET['uid']) . "&page=1";
// Referer value for login request
$loginReferer = "http://www.forum.net/member.php?action=login";
// Note that __DIR__ can also be used in PHP 5.3+
$cookieJar = dirname(__FILE__) . '/cookie.txt';
// The User-Agent string to send
$userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.56 Safari/536.5";
// Create the cURL handle for login
$ch = curl_init($loginUrl);
// Set connection meta
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set header-related options
curl_setopt($ch, CURLOPT_REFERER, $loginReferer);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieJar);
// Set request body
$bodyFields = array(
'username' => $username,
'password' => $password
);
$body = http_build_query($bodyFields);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
// Execute the request
if (!curl_exec($ch)) {
exit("ERROR: Login request failed: " . curl_error($ch));
}
curl_close($ch);
// Create the cURL handle for reputation scrape
$ch = curl_init($reputationUrl);
// Set connection meta
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Set header-related options
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieJar);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieJar);
// Execute the request
if (!$result = curl_exec($ch)) {
exit("ERROR: Reputation scrape request failed: " . curl_error($ch));
}
// Output the result
echo $result;