Some people often ask questions about simulated login. In fact, the principle is very simple. you just need to save the SessionID. Today, it took an hour to write a function for your reference.
Some people often ask questions about simulated login. In fact, the principle is very simple. you just need to save the SessionID. Today, it took an hour to write a function for your reference, the header information returned by the website. The source code is as follows:
-
- /*
- * Get the webpage content
- * Parameter: $ host [in] string
- * Host name (for example, www.shanghaicom)
- * Parameter: $ method [in] string
- * Submission method: POST, GET, HEAD... and add relevant parameters (for detailed syntax, see RFC1945, RFC2068)
- * Parameter: $ str [in] string
- * Submitted content
- * Parameter: $ sessid [in] string
- * PHP SESSIONID
- *
- * @ Return webpage 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 (! Emptyempty ($ sessid ))
- {
- Fputs ($ fp, "Cookie: PHPSESSID = $ sessid; path =/; rn ");
- }
- If (substr (trim ($ method), 0, 4) = "POST ")
- {
- Fputs ($ fp, "Content-Length:". strlen ($ str). "rn"); // do not 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, ""); // "" in 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 $;
- }
-
- /* Construct the username and password string */
- $ 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 "login failed
";
- } Else {
- Echo "login successful
";
- // User. php cannot be accessed because the sessid parameter is not included.
- $ Response = GetWebContent ("localhost", "GET/user. php HTTP/1.0 ",'','');
- Echo $ response ['location']."
"; // Result: error. php? Errcode = 2
-
- // You can access user. php
- $ Response = GetWebContent ("localhost", "GET/user. php HTTP/1.0", '', $ response ['sessid']);
- Echo $ response ['location']."
"; // Result: user. php
- }
- ?>