<!DOCTYPE html>
<html>
<body>
<h1>Curl 模拟登录网站</h1>
<?php
//$cookie_path = './c'; //设置cookie保存路径
//-----登录要提交的表单数据---------------
$vars['username'] = '********';
$vars['pwd'] = '******';
//-------------------------------------
$method_post = true;
//登录提交的url地址(表单中的action的绝对地址)
$url = 'https://login.taobao.com/member/login.jhtml?style=minisimple&from=alimama';
//----------------------------
$ch = curl_init();
$params[CURLOPT_URL] = $url; //请求url地址
$params[CURLOPT_HEADER] = true; //是否返回响应头信息
$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
$params[CURLOPT_USERAGENT] = 'Mozilla/5.0 (Windows NT 5.1; rv:9.0.1) Gecko/20100101 Firefox/9.0.1';
$postfields = '';
foreach ($vars as $key => $value){
$postfields .= urlencode($key) . '=' . urlencode($value) . '&';
}
$params[CURLOPT_POST] = true;
$params[CURLOPT_POSTFIELDS] = $postfields;
//判断是否有cookie,有的话直接使用
if (isset($_COOKIE['cookie_jar']) && ($_COOKIE['cookie_jar'] || is_file($_COOKIE['cookie_jar'])))
{
$params[CURLOPT_COOKIEFILE] = $_COOKIE['cookie_jar']; //这里判断cookie
}
else
{
$cookie_jar = tempnam($cookie_path, 'cookie'); //产生一个cookie文件
$params[CURLOPT_COOKIEJAR] = $cookie_jar; //写入cookie信息
setcookie('cookie_jar', $cookie_jar); //保存cookie路径
}
curl_setopt_array($ch, $params); //传入curl参数
$content = curl_exec($ch); //执行
echo '
'; echo $content; //输出登录结果
//---------登录成功后再次请求其他地址,如果有多个可以循环执行---------
echo '
--------------------------------------------------------------------------------
';
$nexturl = 'www.alimama.com';
$params[CURLOPT_URL] = $nexturl;
$params[CURLOPT_POSTFIELDS] = '';
curl_setopt_array($ch, $params); //传入curl参数
$content = curl_exec($ch); //执行
echo $content; //输出请求结果
//-------------------------------------------------
curl_close($ch); //关闭连接
?>
</body>
</html