PHP settings Session value and cookies Learning example _php instance

Source: Internet
Author: User
Tags readline stringbuffer

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:

The following is login.php, used for requesting login, passing parameters via post, and registering the session if the login is successful.

Copy Code code 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 website </a>";
} else {
echo "-1";
}
}
?>
<body>
<form action= "" method= "POST" >
<input type= "text" name= "username"/>
<input type= "password" name= "password"/>
<input type= "Submit" name= "submit" value= "Submit"/>
</form>
</body>

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";
}
?>

First of all, httpurlconnection this class, the first use of this class directly request content.php page, rightfully returned "-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, and found that there was one sessionid in the same session under the same Web site that wouldn't change.

This is the thing above, 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:

Copy Code code as follows:

public class Nethelper {

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

/**
* Send a request to return the content as a string
* @param URL requested address
* @return The 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 to see for itself to understand
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
* @return The returned content
* */
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 headers, and split, why want 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 to use HttpClient, code similar, I did the same experiment, the result is directly out, HttpClient will automatically management session, the second request does not need to manually set session can login.

Copy Code code 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);

The way to set post parameters is really impersonal ...
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.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 conversation, for each client has generated a SessionID, if it is a successful landing, the server will be recorded well, landing successful SessionID, if the landing failure or the new SessionID, will not be able to verify the landing, this is the session verification log the basic situation.

and 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 SessionID, you must manually set header , HttpClient can intelligently manage sessions without having to manually set up, and in fact Httpclint is similar to a small browser in a program.

Maximum slot point I think that's it. The two classes set post parameters in a way that is 2B and inconvenient ...

In addition HttpClient cannot send two requests at the same time, if one request is not finished or closed, another request is opened immediately. We'll report a warning, cut a picture.

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

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.