• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

用PHP模拟登陆_php

php 搞代码 7年前 (2018-06-21) 192次浏览 已收录 0个评论

  经常会有人问模拟登陆的问题,其实原理很简单,只要把SessionID保存下来就可以了,今天花了一个小时的时间写了一个函数,供大家参考,网站返回的头信息,具体网站具体分析。

  源代码:

<?php
/* 
* 得到网页内容 
* 参数:$host [in] string
*      主机名称(例如: http://www.imsorry.com.cn)
* 参数:$method [in] string

http://www.gaodaima.com/48028.html用PHP模拟登陆_php

*      提交方法:POST, GET, HEAD … 并加上相应的参数( 具体语法参见 RFC1945,RFC2068 )
* 参数:$str [in] string
*      提交的内容
* 参数:$sessid [in] string
*      PHP的SESSIONID
*
* @返回 网页内容 string
*/
function GetwebContent($host, $method, $str, $sessid = ”)
{
    $ip = gethostbyname($host);
    $fp = fsockopen($ip, 80);
    if (!$fp) return;
    fputs($fp, “$method/r/n”);
    fputs($fp, “Host: $host/r/n”);
    if (!empty($sessid))
    {
        fputs($fp, “Cookie: PHPSESSID=$sessid; path=/;/r/n”);
    }
    if ( substr(trim($method),0, 4) == “POST”)
    {
        fputs($fp, “Content-Length: “. strlen($str) . “/r/n”); //  别忘了指定长度
    }
    fputs($fp, “Content-Type: application/x-www-form-urlencoded/r/n/r/n”);
    if ( substr(trim($method),0, 4) == “POST”)
    {
        fputs($fp, $str.”/r/n”);
    }
    while(!feof($fp))
    {
        $response .= fgets($fp, 1024);
    }
    $hlen = strpos($response,”/r/n/r/n”); // linux下是 “/n/n”
    $header = substr($response, 0, $hlen);
    $entity = substr($response, $hlen + 4);
    if ( preg_match(‘/PHPSESSID=([0-9a-z]+);/i’, $header, $matches))
    {
        $a[‘sessid’] = $matches[1];
    }
    if ( preg_match(‘/Location: ([0-9a-z/_/?/=/&/#/.]+)/i’, $header, $matches))
    {
        $a[‘location’] = $matches[1];
    }
    $a[‘content’] = $entity;    
    fclose($fp);
    return $a;
}

/* 构造用户名,密码字符串 */
$str = (“username=test&password=test”);
$response = GetWebContent(“localhost”,”POST /login.php HTTP/1.0″, $str);
echo $response[‘location’].$response[‘content’].”<br>”;
echo $response[‘sessid’].”<br>”;
if ( preg_match(‘/error/.php/i’,$response[‘location’]))
{
    echo “登陆失败<br>”;
} else {
    echo “登陆成功<br>”;
    // 不可以访问user.php,因为不带sessid参数
    $response = GetWebContent(“localhost”,”GET /user.php HTTP/1.0″, ”, ”);
    echo $response[‘location’].”<br>”; // 结果:error.php?errcode=2

    // 可以访问user.php
    $response = GetWebContent(“localhost”,”GET /user.php HTTP/1.0″, ”, $response[‘sessid’]);
    echo $response[‘location’].”<br>”; // 结果:user.php
}
?>

欢迎大家阅读《用PHP模拟登陆_php》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:用PHP模拟登陆_php
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址