Learning example of setting session values and cookies in php

Source: Internet
Author: User

Step 1: first write a login page and a content page locally (only after logging in. The code is roughly as follows:

The following is login. php, which is used for request login. parameters are passed through post. If the login is successful, the session will be registered.

Copy codeThe Code is as follows:
<? Php
Session_start ();

If (isset ($ _ POST ['username']) {
$ Username = $ _ POST ['username'];
$ Password = $ _ POST ['Password'];

If ($ username = 'admin' & $ password = 'admin '){
$ _ SESSION ['username'] = $ username;
Echo "<a href = 'content. php'> enter the website </a> ";
} Else {
Echo "-1 ";
}
}
?>
<Html>
<Body>
<Form action = "" method = "post">
<Input type = "text" name = "username"/>
<Input type = "password" name = "password"/>
<Input type = "submit" name = "submit" value = "submit"/>
</Form>
</Body>
</Html>

The following is content. php, which verifies the session and is used as the content page of the website. You can view the correct content only after logging on to the website.

Copy codeThe Code is as follows:
<? Php
Session_start ();
If (isset ($ _ SESSION ['username']) {
Echo "login OK ";
} Else {
Echo "not login ";
}
?>

Next, let's talk about the HttpURLConnection class. First, use this class to directly request the content. php page, and then return "-1 ". If you first use this class to request login. php, and pass the correct parameters, it will show that the login is successful, and then use this class to request content. php still returns "-1". Obviously, HttpURLConnection does not record the login status, or the server knows the person who just logged in successfully, but this request content. php users still don't know each other. This indicates that each request of HttpURLConnection is independent, and is a new request, or each request is a new session ).

Then I used chrome to open the test webpage I wrote. I found that there was a sessionid in the same session under the same website.

This is the above thing. If a page is opened, the value of this SESSIONID will not change no matter how you refresh it or jump to another website under this server, however, if you turn off all the pages under the server and re-open such a page, the SESSIONID value will be re-generated.

Therefore, when HttpURLConnection is used, log on to login for the first time. php is a sessionid. the login is successful. The server remembers the situation where SESSIONID is A (assuming A is good), but then requests content. in php, SESSIONID Is Not A, and the server considers that you have not logged on, so it displays "-1 ". After understanding the problem, you only need to add the SESSIONID header to the HttpURLConnection request. The final code is as follows:

Copy codeThe Code is as follows:
Public class NetHelper {

/**
* SESSIONID
**/
Private String sessionId = "";

/**
* Send a request to return the content in a string
* @ Param url the requested address
* @ Return returned content
**/
Public String request (String url) throws IOException {
URL uUrl = new URL (url );
HttpURLConnection huc = (HttpURLConnection) uUrl. openConnection ();
Huc. addRequestProperty ("Cookie", sessionId); // Why is "Cookie"? Chrome opens F12 and you will understand it.
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 a login request and save the SESSIONID
* @ Param url: the address of the login request
* @ Return returned content
**/
Public String login (String url) throws IOException {
URL uUrl = new URL (url );
HttpURLConnection huc = (HttpURLConnection) uUrl. openConnection ();

// SET THE REQUEST METHOD
Huc. setRequestMethod ("POST ");

// Set the post Parameter
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 ();

// Extract from headers and split the headers. Why do we need to split the headers? Open F12 and you will understand it.
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;
}
}

The next step is to use HttpClient. The code is similar. After I perform the same experiment, the result is displayed directly. HttpClient will automatically manage sessions, for the second request, you do not need to manually set the Session to log on.

Copy codeThe Code is as follows:
Public class NetClient {

Private HttpClient client = null;

Public NetClient (){
Client = new DefaultHttpClient ();
}

Public String request (String url) throws ClientProtocolException, IOException {
HttpPost post = new HttpPost (url );
HttpResponse res = client.exe cute (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 );

// The post parameter setting method is really unfriendly ......
ArrayList <NameValuePair> pa = new ArrayList <NameValuePair> ();
Pa. add (new BasicNameValuePair ("username", "admin "));
Pa. add (new BasicNameValuePair ("password", "admin "));
Post. setEntity (new UrlEncodedFormEntity (pa, "UTF-8 "));

HttpResponse res = client.exe cute (post );

BufferedReader br = new BufferedReader (new InputStreamReader (res. getEntity (). getContent ()));
String data = "";
String line = "";
While (line = br. readLine ())! = Null ){
Data = data + line;
}
Return data;
}
}

In conclusion, the Session verification method is to generate a SESSIONID for each client in a Session. If a Session is successfully logged in, the server will record it, if the login fails or the new SESSIONID, the login cannot be verified. This is the basic situation for SESSION verification login.

Both HttpURLConnection and HttpClient can be used for network requests, but they are slightly different. Each request of HttpuRLConnection is a new session. If you need to verify the SESSIONID, you must manually set the Header, httpClient can intelligently manage sessions without manual settings. In fact, HttpClint is similar to a small browser in a program.

The biggest slot I think is that the methods for Setting post parameters for these two classes are both 2B and not convenient at all ......

In addition, HttpClient cannot send two requests at the same time. If a request is not completed or closed, another request is enabled immediately. A warning will be reported. Cut a picture.

So I have taken a comprehensive consideration and try to use HttpURLConnection in the future.

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.