Cookie and Session are common methods for website login verification. Regardless of the Forum or Weibo, they all rely on cookies and sessions to complete their work.
Here we will not specifically introduce the concepts of cookies and Sessions. We can simply regard them as temporary keys for enabling different network resources.
The following describes how to operate cookies and sessions in PHP.
Cookie:
In PHP, we can use the setcookie () function to set the cookie. Note that the setcookie function must be placed before the
Generally, we set cookies like this.
Set cookie
The code is as follows: |
Copy code |
<? Php Setcookie ("username", "Ku_Andrew", time () + 3600 ); ?> |
Username is the name of our cookie, while Ku_Andrew is the value of username, and time () + 3600 is the cookie expired in an hour.
Now we use $ _ COOKIE to create an instance.
Set and read cookies
The code is as follows: |
Copy code |
<? Php $ Username = $ _ COOKIE ['username']; If ($ username = "") { Setcookie ("username", "Ku_Andrew", time () + 3600 ); Echo "we 've not found your username from your cookie "; Echo "but now we 've give it to you, please refresh this page "; Die ("<a href = $ PHP_SELF> kick me and refresh </a> "); } Else { Echo ("hello $ usernama "); } ?> |
To make more complex judgments, such as user login, we can add the retrieved values from the database to the IF statement.
Session:
Unlike cookies, sessions are stored on the server, and the Session will automatically perish as the browser closes, resulting in a short life cycle. In PHP, we use the session_start () function to start the session. Like setting cookies, we must use this function before the
Set and read Sessions
The code is as follows: |
Copy code |
<? Php Session_start (); If ($ _ SESSION ['pid '] = "") { $ _ SESSION ['pid '] = 1; } Else { $ _ SESSION ['pid '] + = 1; } Echo "this is your $ _ SESSION ['pid '] times watching this page "; ?> |
This is a simple web page counter, which is counted by setting the pid. In the first judgment, if the session is empty, it is set to read the session and fed back to the user. Each subsequent access will be submitted to the user based on the original session.