最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

用PHP模拟登陆

时间:2014-06-09 16:39来源: 作者: 点击: 次
经常会有人问模拟登陆的问题,其实原理很简单,只要把SessionID保存下来就可以了,今天花了一个小时的时间写了一个函数,供大家参考,网站返回的头信息,具体网站具体分析,源代码: ?php

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

  1. <?php 
  2. /* 
  3. * 得到网页内容 
  4. * 参数:$host [in] string 
  5. * 主机名称(例如: www.etoow.com) 
  6. * 参数:$method [in] string 
  7. * 提交方法:POST, GET, HEAD ... 并加上相应的参数( 具体语法参见 RFC1945,RFC2068 ) 
  8. * 参数:$str [in] string 
  9. * 提交的内容 
  10. * 参数:$sessid [in] string 
  11. * PHP的SESSIONID 
  12. * 
  13. * @返回 网页内容 string 
  14. */ 
  15. function GetWebContent($host, $method, $str, $sessid = '') 
  16. { 
  17. $ip = gethostbyname($host); 
  18. $fp = fsockopen($ip, 80); 
  19. if (!$fp) return; 
  20. fputs($fp, "$methodrn"); 
  21. fputs($fp, "Host: $hostrn"); 
  22. if (!emptyempty($sessid)) 
  23. { 
  24. fputs($fp, "Cookie: PHPSESSID=$sessid; path=/;rn"); 
  25. } 
  26. if ( substr(trim($method),0, 4) == "POST") 
  27. { 
  28. fputs($fp, "Content-Length: ". strlen($str) . "rn"); // 别忘了指定长度 
  29. } 
  30. fputs($fp, "Content-Type: application/x-www-form-urlencodedrnrn"); 
  31. if ( substr(trim($method),0, 4) == "POST") 
  32. { 
  33. fputs($fp, $str."rn"); 
  34. } 
  35. while(!feof($fp)) 
  36. { 
  37. $response .= fgets($fp, 1024); 
  38. } 
  39. $hlen = strpos($response," "); // LINUX下是 " " 
  40. $header = substr($response, 0, $hlen); 
  41. $entity = substr($response, $hlen 4); 
  42. if ( preg_match('/PHPSESSID=([0-9a-z] );/i', $header, $matches)) 
  43. { 
  44. $a['sessid'] = $matches[1]; 
  45. } 
  46. if ( preg_match('/Location: ([0-9a-z_?=&#.] )/i', $header, $matches)) 
  47. { 
  48. $a['location'] = $matches[1]; 
  49. } 
  50. $a['content'] = $entity; 
  51. fclose($fp); 
  52. return $a; 
  53. } 
  54.  
  55. /* 构造用户名,密码字符串 */ 
  56. $str = ("username=test&password=test"); 
  57. $response = GetWebContent("localhost","POST /login.php HTTP/1.0", $str); 
  58. echo $response['location'].$response['content']."<br>"; 
  59. echo $response['sessid']."<br>"; 
  60. if ( preg_match('/error.php/i',$response['location'])) 
  61. { 
  62. echo "登陆失败<br>"; 
  63. } else { 
  64. echo "登陆成功<br>"; 
  65. // 不可以访问user.php,因为不带sessid参数 
  66. $response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', ''); 
  67. echo $response['location']."<br>"; // 结果:error.php?errcode=2 
  68.  
  69. // 可以访问user.php 
  70. $response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', $response['sessid']); 
  71. echo $response['location']."<br>"; // 结果:user.php 
  72. } 
  73. ?> 
(责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容