用PHP模擬登陸
來源:程序員人生 發布時間:2014-01-05 17:09:56 閱讀次數:2849次
經常會有人問模擬登陸的問題,其實原理很簡單,只要把SessionID保存下來就可以了,今天花了一個小時的時間寫了一個函數,供大家參考,網站返回的頭信息,具體網站具體分析,源代碼:
- <?php
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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," ");
- $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>";
-
- $response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', '');
- echo $response['location']."<br>";
-
-
- $response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', $response['sessid']);
- echo $response['location']."<br>";
- }
- ?>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈