PHP Set session value and Cookie Learning example _php Tutorial

Source: Internet
Author: User
The first step: Write a landing page and a content page locally (login to go in). The code is roughly as follows:

The following is login.php, used to request the login, pass the parameters via post, if the login success will register session.

Copy the Code code as follows:
Session_Start ();

if (isset ($_post[' username ')) {
$username = $_post[' username ');
$password = $_post[' password ');

if ($username = = ' Admin ' && $password = = ' admin ') {
$_session[' username '] = $username;
echo "Enter the website";
} else {
echo "-1";
}
}
?>





Here is content.php, will verify the session, used when the site's content page, logged in to see the correct content.

Copy the Code code as follows:
Session_Start ();
if (isset ($_session[' username ')) {
echo "Login OK";
} else {
echo "Not login";
}
?>

Next the first httpurlconnection this class, first use this class directly request content.php page, rightfully returned "1". If you first use this class to request login.php, and pass the correct parameters, it will show the success of the login, this time again to use this class request content.php, still return "1", it is clear that HttpURLConnection did not record the state of our landing, Or the server knows the person who just landed successfully, but this time the request content.php it still does not know. This means that each request of httpurlconnection is separate, a new request, or a new session for each of the requests that are made.

Then I used Chrome to open the Web page of the test that I wrote myself, and found that in the same site, there was a sessionid in the same session.

This is the above thing, if you open a page, regardless of refresh, or jump to the other sites under the server, this SessionID value will not change, but if you turn off all the pages under this server, and then reopen such a page, The value of this sessionid is regenerated.

So in the case of HttpURLConnection, The first landing login.php is a SessionID, indeed landed successfully, the server remembers is SessionID for a situation (assuming a good), but again 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 when the request, add SessionID this head on the line. 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 as a string
* @param URL Request address
* Content returned by @return
* */
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 open F12 See for yourself
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 Login request Address
* Content returned by @return
* */
public string login (string url) throws IOException {
URL uurl = new URL (URL);
HttpURLConnection Huc = (httpurlconnection) 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 ();

Remove from the headers, and split, why to split, Chrome open F12 see for yourself.
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 results are directly out, HttpClient will automatically manage the session, the second request does not need to manually set the session can 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.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);

How to set the post parameters is really not human ah ...
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.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;
}
}

Finally, the method of session verification is in a session, for each client has generated a SessionID, if the successful landing, the server will be logged, the successful landing SessionID, if the login failed or the new SessionID, will not be able to verify the login, this is the session to verify the basic situation.

While the HttpURLConnection and httpclient two classes can be used for network requests, but slightly different, httpurlconnection each request is a new session, if you need to verify the SessionID, you have to manually set the header , HttpClient can manage the session intelligently, does not need to be set manually, in fact Httpclint is similar to a small browser in a program.

Largest slot I think it's just these two classes. The way to set the post parameters is 2B is not convenient ...

In addition, HttpClient cannot send two requests at the same time, and if a request has not been completed or closed, another request will be opened immediately. You'll get a warning, cut a picture.

So I considered the next, or try to use the HttpURLConnection bar.

http://www.bkjia.com/PHPjc/744333.html www.bkjia.com true http://www.bkjia.com/PHPjc/744333.html techarticle The first step: Write a landing page and a content page locally (login to go in). The code is roughly as follows: The following is login.php, used to request login, pass 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.