1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| /**
* 先登录(登录需要获取 token)
*/
// 创建临时存放 cookie 的文件
$cookie_file = tempnam('./temp', 'cookie');
$login_url = 'http://..';
$ch = curl_init($login_url);
// 是否将头文件的信息作为数据流输出
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
// 先获取 token,已在登录页面设置好
curl_setopt($ch, CURLOPT_POST, array('curl_token' => 'curl_token'));
$token = curl_exec($ch);
// 登录
curl_setopt($ch, CURLOPT_POST, array(
'submit' => '登录',
'token' => $token,
'username' => 'xxx',
'password' => 'xxx',
));
// 连接结束后,比如,调用 curl_close 后,保存 cookie 信息
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
// 再次连接,这次是登录
curl_exec($ch);
curl_close($ch);
/**
* 利用登录获取的登录 cookie,访问页面
*/
$url = 'http://...';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
// 模拟登录状态的 cookie
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_exec($ch);
curl_close($ch);
|