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

Jul 13, 2016 am 10:35 AM
cookies php session

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传递...
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1665
14
PHP Tutorial
1269
29
C# Tutorial
1249
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

See all articles