用PHP類比登陸_PHP教程

來源:互聯網
上載者:User
經常會有人問類比登陸的問題,其實原理很簡單,只要把SessionID儲存下來就可以了,今天花了一個小時的時間寫了一個函數,供大家參考,網站返回的頭資訊,具體網站具體分析。

  原始碼:

/*
* 得到網頁內容
* 參數:$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']."
";
echo $response['sessid']."
";
if ( preg_match('/error.php/i',$response['location']))
{
echo "登陸失敗
";
} else {
echo "登陸成功
";
// 不可以訪問user.php,因為不帶sessid參數
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', '');
echo $response['location']."
"; // 結果:error.php?errcode=2

// 可以訪問user.php
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', $response['sessid']);
echo $response['location']."
"; // 結果:user.php
}
?>

http://www.bkjia.com/PHPjc/631970.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631970.htmlTechArticle經常會有人問類比登陸的問題,其實原理很簡單,只要把SessionID儲存下來就可以了,今天花了一個小時的時間寫了一個函數,供大家參考...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.