经常会有人问模拟登陆的问题,其实原理很简单,只要把SessionID保存下来就可以了,今天花了一个小时的时间写了一个函数,供大家参考,网站返回的头信息,具体网站具体分析,源代码:
- <?php
- /*
- * 得到网页内容
- * 参数:$host [in] string
- * 主机名称(例如: www.etoow.com)
- * 参数:$method [in] string
- * 提交方法: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, "$methodrn");
- fputs($fp, "Host: $hostrn");
- if (!emptyempty($sessid))
- {
- fputs($fp, "Cookie: PHPSESSID=$sessid; path=/;rn");
- }
- if ( substr(trim($method),0, 4) == "POST")
- {
- fputs($fp, "Content-Length: ". strlen($str) . "rn"); // 别忘了指定长度
- }
- fputs($fp, "Content-Type: application/x-www-form-urlencodedrnrn");
- if ( substr(trim($method),0, 4) == "POST")
- {
- fputs($fp, $str."rn");
- }
- while(!feof($fp))
- {
- $response .= fgets($fp, 1024);
- }
- $hlen = strpos($response," "); // LINUX下是 " "
- $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
- }
- ?>
波比源码 – 精品源码模版分享 | www.bobi11.com
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 本站源码并不保证全部能正常使用,仅供有技术基础的人学习研究,请谨慎下载
8. 如遇到加密压缩包,请使用WINRAR解压,如遇到无法解压的请联系管理员!
波比源码 » 用PHP模拟登陆
波比源码 » 用PHP模拟登陆