How to Set session values and cookies in php _ PHP Tutorial

Source: Internet
Author: User
Example of how to set session values and cookies in php. 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. pass the first step through post: first write a login page and a content page locally (login before entering. 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:


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 Pa = new ArrayList ();
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.

Login. The code is roughly as follows: The following is login. php, which is used for request login and passed through post...

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.