Learning example of setting session values and cookies in php

Source: Internet
Author: User
I have never understood the Session and the login verification of cookies. I tried HttpURLConnection and HttpClient yesterday, respectively, to understand the mechanism and

I have never understood the Session and the login verification of cookies. I tried HttpURLConnection and HttpClient yesterday, respectively, to understand the mechanism and

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.

The Code is as follows:


Session_start ();

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

If ($ username = 'admin' & $ password = 'admin '){
$ _ SESSION ['username'] = $ username;
Echo "go to the website ";
} Else {
Echo "-1 ";
}
}
?>





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.

The Code is as follows:


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:

The 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.

The Code is as follows:

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.