Simulate login with PHP_PHP tutorial
Jul 13, 2016 am 10:59 AMPeople often ask about simulated login. In fact, the principle is very simple. Just save the SessionID. I spent an hour today writing a function for your reference. The header information returned by the website , specific analysis of specific websites.
Source code:
<?php
/*
* Get web content
* Parameter: $host [in] string
* Host name (for example: www.etoow.com)
* Parameter: $method [in] string
* Submission method: POST, GET, HEAD... and add corresponding parameters (see RFC1945, RFC2068 for specific syntax)
* Parameter: $str [in] string
* Submitted content
* Parameter: $sessid [in] string
* PHP SESSIONID
*
* @return web page content 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"); // Don't forget to specify the length
}
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," "); // Under LINUX it is " "
$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;
}
/* Construct username and password string */
$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 "Login failed<br>";
} else {
echo "Login successful<br>";
// User.php cannot be accessed because there is no sessid parameter
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', '');
echo $response['location']."<br>"; // Result: error.php?errcode=2
// Can access user.php
$response = GetWebContent("localhost","GET /user.php HTTP/1.0", '', $response['sessid']);
echo $response['location']."<br>"; // Result: user.php
}
?>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
