php模拟登录保存登录cookie信息的例子

发布时间:2020-10-09编辑:脚本学堂
本文介绍了php模拟登录并保存登录cookie信息的方法,php模拟登录的小例子,需要的朋友参考下。

例子,php模拟登录网站,并可以保存登录cookie信息。
 

复制代码 代码示例:

<?php
function write_cookie($cookie,$db)
{
$fp = fopen(‘/tmp/cookie.txt’, ‘w’);
fwrite($fp, $cookie);
fclose($fp);
}

function get_cookie($db)
{

$handle = @fopen(“/tmp/cookie.txt”, “r”);
if ($handle) {
while (($buffer = fgets($handle, 4096)) !== false) {
$cookie = trim($buffer);
}
fclose($handle);
}

return $cookie;
}

function openhttp($url,$post=”,$cookie=”,$agent=”,$referfer=”, $origin=”", $host=”", $content_type = “”, $is_header=1){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);

$header = array();
if(!empty($host)) {
$header[] = “Host:zzip.ip518.com:900″;
}

if(!empty($origin)) {
$header[] = “Origin:http://zzip.ip518.com:900″;
}
if(!empty($content_type)) {
$header[] = “Content-Type:application/x-www-form-urlencoded”;
}

if(count($header)) {
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
}

if(!empty($cookie)) curl_setopt($ch, CURLOPT_COOKIE,$cookie);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
if(!empty($referfer)) curl_setopt($ch, CURLOPT_REFERER, $referfer);
curl_setopt($ch, CURLOPT_USERAGENT, “Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31″);
if(!empty($post)) curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
if(!empty($post)) curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
if($is_header) curl_setopt($ch, CURLOPT_HEADER, 1);

$return = curl_exec($ch);
curl_close($ch);
return $return;
}

function login($username, $password, $login_url = “http://zzip.ip518.com:900/login.asp”)
{
$content=”;
$cookies=”;
$content = openhttp(“http://zzip.ip518.com:900/login.asp”, “name=$username&pass=$password&enter=”);
$cookies = get_items($content, array(“Set-Cookie: “), array(“;”));

$cookie = implode(“;”, $cookies);
write_cookie($cookie);

return $cookie;
}

login(“账号”, “密码”);

说明:
登录成功后把cookie信息写入文件/tmp/cookie.txt,下次直接读取这个文件,以后操作此cookie文件,即可实现登录。

>>> 更多 php模拟登录 文章,专题链接:php模拟登录 php curl模拟登录教程大全