PHP settings Session value and cookies learning example

Source: Internet
Author: User
Tags readline split stringbuffer

  has not been understanding session,cookies what is going on in the end, yesterday, respectively, with HttpURLConnection and httpclient two classes to experiment, The basic understanding of the session to verify the mechanism of landing and the difference between these two classes. Now let's share it with you.

The first step: first in the local write a landing page and a content page (log in to enter) bar. The code is roughly as follows:   Below is login.php, used to request landing, pass the parameters through the post, if the landing will register the session successfully.   Code as follows: <?php session_start ();   if (isset ($_post[' username ')) {    $username = $_post[' username '];     $password = $_post[' pa ssWOrd '];       if ($username = ' admin ' && $password = ' admin ') {        $_session[' US Ername '] = $username;         echo "<a href= ' content.php ' > into the website </a>";    } else {        echo "-1";    }}?> <html> <body> <form A ction= "" method= "post" > <input type= "text" name= "username"/> <input type= "password" name= "password"/> & Lt;input type= "Submit" name= "submit" value= "Submit"/> </form> </body> </html>       The following is content.php, will verify the session, used when the site's content page, log in to see the correct content.     Copy code code as follows: <?php session_start (); if (isset ($_session[' username ')) {   echo "Login OK"; else {    echo ' not login ';}?>     HttpURLConnection This class first, use this class to directly request the content.php page, and rightfully return the " -1 ". If the first use of this class to request login.php, and pass the correct parameters, will show the landing success, this time to use this class request content.php, still return "-1", obviously, HttpURLConnection did not record the status of our landing, Or the server knew just landed the successful person, but this request content.php person it still does not know. This shows that each request of httpurlconnection is independent, a new request, or that each request is a new conversation (session).   Then I used Chrome to open the test page I wrote myself, and found that there was one sessionid in the same session under the same Web site that wouldn't change.   is the above thing, if you open a page, regardless of the refresh, or jump to the other sites under this server, the value of this sessionid will not change, but if you turn off all the pages under the server, and then reopen such a page, The value of this sessionid is regenerated.   So with the HttpURLConnection case, The first landing login.php is a SessionID, did login successfully, the server will remember SessionID for a situation (assuming that is a good), but then to request content.php, SessionID is not a, the server thinks you did not login, so it shows "-1". The problem is clear, then only need to httpurlconnection the request, add SessionID this head on the line. The final code is as follows:     Code as follows: public class Nethelper {     /**      * SESSIONID   &NBSP ;  * *     private String sessionId = "";      /**      * send a request to return the content as a string to      * @param URL requested address     &NBSP ; * @return Content returned      */    public string request (String URL) throws IOException {  &nbs P     URL uurl = new URL (URL);         httpurlconnection Huc = (httpurlconnection) uurl.openconnection ();         Huc.addrequestproperty ("Cookie", sessionId);    //Why is "Cookie", the chrome opens F12 oneself to see to understand the         huc.connect ();         BufferedReader br = new BufferedreaDer (New InputStreamReader (Huc.getinputstream ()));         String data = "";         String line = "";         while (line = Br.readline ())!= null) {             data = Data + line;        }         return data;    }      /**      * send login request and save SessionID      * @param URL Login please Address      * @return return      */    public String login (String url) throws IOE xception {        URL uurl = new URL (URL);         httpurlconnection Huc = (HTTPU rlconnection) uurl.openconnection ();          //Set Request mode         Huc.setrequestmethod ("POST");          //Set Post parameters         StringBuffer params = new StringBuffer ();         pArams.append ("Username="). Append ("admin"). Append ("&"). Append ("password="). Append ("admin");         byte[] bytes = params.tostring (). GetBytes ();         Huc.getoutputstream (). write (bytes);           huc.connect ();          //removed from the headers, and split, why to split, Chrome open F12 take a look at it to understand the         string[] AAA = Huc.getheaderfield ("Set-cookie"). Split (";");         sessionId = aaa[0];           BufferedReader br = new BufferedReader (New InputStreamReader (Huc.getinputstream ()));         String data = "";         String line = "";         while (line = Br.readline ())!= null) {             data = Data + line;        }         return data;    }     Next is the use of HttpClient, code similar, I did the same experiment, the result is directly out, HTTPCLIENT will automatically manage sessions, the second request does not need to manually set the session can be logged on.   Code as follows: public class Netclient {      private httpclient client = null;        PU Blic netclient () {        client = new Defaulthttpclient ();    }       Publ IC string request (string url) throws Clientprotocolexception, IOException {        httppost post = NE W httppost (URL);         HttpResponse res = Client.execute (POST);           BufferedReader br = new BufferedReader (new InputStreamReader (res.getentity). GetContent ()));         String data = "";         String line = "";         while (line = Br.readline ())!= null) {             data = Data + line;        }         return data;    }       public String login (String URL) throws Clientprotocolexception, IOException {        HttpPost post = new HttpPost (URL);     &NBSP ;    //Setting post parameters is really impersonal ...         arraylist<namevaluepair> pa = new Arraylist<na Mevaluepair> ();         Pa.add (new Basicnamevaluepair ("username", "admin"));         Pa.add (new Basicnamevaluepair ("Password", "admin"));         post.setentity (New Urlencodedformentity (PA, "UTF-8"));           HttpResponse res = Client.execute (POST);           BufferedReader br = new BufferedReader (new InputStreamReader (res.getentity). GetContent ()));         String data = "";         String line = "";         while (line = Br.readline ())!= null) {             data = Data + line;        }       &NBsp return data;    }       Finally, the method of session verification is in a conversation, for each client has generated a SessionID, if the successful landing, the server will be recorded well, Landing successful SessionID, if the landing failure or new SessionID, will not be able to verify the landing, this is the session to verify the basic situation of landing.   HttpURLConnection and httpclient These two classes can be used for network requests, but slightly different, httpurlconnection each request is a new session, if you need to verify SessionID, You have to manually set the header,httpclient can be intelligent management session, do not need to manually set, in fact, Httpclint is similar to a small browser in the program.   Maximum slot point I think it's the two classes. Setting post parameters is 2B.   Other httpclient cannot send two requests at the same time, if one request is not finished or closed, another request is opened immediately. You'll report a warning, cut a picture       So I think about it, and try to use HttpURLConnection.  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.