Home >Backend Development >PHP Tutorial >Learning example of setting session value and cookies in php_PHP tutorial

Learning example of setting session value and cookies in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:35:201060browse

Step one: First write a login page and a content page locally (you can only enter after logging in). The code is roughly as follows:

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

Copy code The code is as follows:

Copy code

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 it will return "-1" as it should. If you first use this class to request login.php and pass the correct parameters, it will show that the login is successful. At this time, if you use this class to request content.php, it will still return "-1". Obviously, HttpURLConnection is not recorded. The status of our login, or the server knows the person who has just successfully logged in, but it still does not know the person who requested content.php this time. This shows that each request of HttpURLConnection is independent and a new request, or each request is a new session.

Then I used Chrome to open the test webpage I wrote myself, and found that on the same website and in the same session, there is a sessionid that will not change.
This is the thing above. If you open a certain page, no matter how you refresh it or jump to other websites under this server, the value of this SESSIONID will not change. But if you close all the pages under this server, When such a page is reopened, the SESSIONID value will be regenerated.

So when using HttpURLConnection, the first login.php is a SESSIONID, and the login is indeed successful. The server remembers the SESSIONID as A (assuming it is A), but then requests content.php, the SESSIONID is not A, and the server thinks you are not logged in, so it displays "-1". Now that the problem is understood, you only need to add the SESSIONID header to the HttpURLConnection request. The final code is as follows:

Learning example of setting session value and cookies in php_PHP tutorialCopy code

The code is as follows:


public class NetHelper {

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

    /**
* Send a request and return the content as a string
* @param url 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);    //为什么是“Cookie”,Chrome打开F12自己看看就明白了
        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 The returned content
**/
    public String login(String url) throws IOException {
        URL uUrl = new URL(url);
        HttpURLConnection huc = (HttpURLConnection) uUrl.openConnection();

        //设置请求方式
        huc.setRequestMethod("POST");

        //设置post参数
        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();

        //从headers中取出来,并分割,为什么要分割,Chrome打开F12自己看看就明白了
        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;
    }
}

接下来就是使用HttpClient,代码类似的,我做了相同的实验,结果就直接出来了,HttpClient会自动的管理Session,第二次请求不需要手动去设置Session就可以登录上。

复制代码 代码如下:

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);

        //设置post参数的方式还真是不人性化啊……
        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;
    }
}

最后总结一下,Session验证的方式是在一次会话中,为每一个客户端都生成了一个SESSIONID,如果是成功登陆的,服务器端就会记录好,登陆成功的SESSIONID,如果登陆失败或者新的SESSIONID,都将无法验证登陆,这就是SESSION验证登陆的基本情况。

而HttpURLConnection和HttpClient这两个类都可以用来网络请求,但稍有不同,HttpuRLConnection每一次请求都是新的会话,如果需要去验证SESSIONID,就必须手动的去设置Header,HttpClient就能智能的管理Session,不需要手动设置,实际上HttpClint就类似于一个程序中的小浏览器。

最大的槽点我觉得就是这两个类设置post参数的方式都很2B一点都不方便……

另外HttpClient不能同时发送两次请求,如果一个请求还没有结束或者关闭,又马上开启另一个请求。就会报警告,截个图吧

Learning example of setting session value and cookies in php_PHP tutorial

所以我综合考虑了下,以后还是尽量都使用HttpURLConnection吧。

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/744333.htmlTechArticle第一步:先在本地写一个登陆页面和一个内容页面(登陆了才能进去)吧。代码大致如下: 下面是login.php,用于请求登陆的,通过post传递...