程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 用PHP模擬登陸

用PHP模擬登陸

編輯:關於PHP編程

經常會有人問模擬登陸的問題,其實原理很簡單,只要把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 (!empty($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
}
?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved