Php uses cookies and user sessions. PHP Cookie implements session _ php Tutorial

Source: Internet
Author: User
Php uses Cookie implementation and user session method, and phpcookie implements session. Php uses cookies and user sessions. phpcookie implements session. This article describes how php uses cookies and user sessions. Share it with you for your reference. Specific analysis of php uses Cookie implementation and user session methods, phpcookie implements session

This article describes how php uses cookies and user sessions. Share it with you for your reference. The specific analysis is as follows:

PHP contains many functions that can be used to manage and record user information, including simple cookies and comprehensive user sessions. Sessions use the built-in PHP technology to make the save state as simple as referencing a super global variable.

1. Cookie introduction

We can use cookies with PHP scripts to store small user information. A Cookie is a small amount of data stored by a user's browser. it is consistent with a request from a server or script. Using a user's browser, a single host can request to save 20 cookies. Each cookie contains a name, value, expiration date, and host and path information. The size limit of a single cookie is 4 kB.

After a cookie is set, only the requesting host can read data, which ensures that user privacy is respected. In addition, you can configure your browser to accept or reject all cookie requests. Therefore, cookies should be used in a moderate manner and should not be used as a basic element in an environment that is not designed to warn users.

If the Web browser is configured to store cookies, it will keep cookie-based information until the expiration date. If you use a browser to browse any page that matches the cookie path and domain, it resends the cookie to the server. Then, a PHP script can access cookies. cookies can be accessed in the environment variable HTTP_COOKIE or as part of the $ cookie hyper-global variable in three ways:

The code is as follows:

Echo $ _ SERVER ["HTTP_COOKIE"];
Echo getenv ("HTTP_COOKIE ");
Echo $ _ COOKIE ["vegetable"];

2. use PHP to set a cookie

We can set a cookie in a PHP script in two ways. First, use the header () function to set the SetCookie header. The Header () function requires a string that is subsequently included in the Header of the server response. Because the header will be automatically sent for you, the header () must be called before the hot river output sent to the browser.

The code is as follows:

Head ("Set Cookie: vegetable = artichoke; expires = Tue, 07-Mar-06 14:39:58 GMT; path =/; domain = yourmain.com ");


Although there is no difficulty, this cookie setting method requires us to write a function to build the header string. It is not a very difficult task to format a date and encode the name/value pair as in this example, but it is a repetitive task because PHP provides a function to do this, this is setcookie ().

The Setcookie () function outputs a Set-Cookie header as its name shows. Therefore, it should be called before any other content is sent to the browser. This function accepts the cookie name, cookie value, UNIX timestamp format expiration date, path, domain, and an integer. if the cookie is sent only through a secure connection, set the value of this integer to 1. all parameters of this function are optional except the first parameter.

The code is as follows:

<? Php
Setcookie ("vegetable", "artichoke", time () + 3600, "/", ".yourdomain.com", 0 );

If (isset ($ _ COOKIE ["vegetable"]) {
Echo"

Hello again, you have chosen: ". $ _ COOKIE [" vegetable "].".

";
}
Else {
Echo"

Hello you. This may be your first visit.

";
}
?>


Even if we set the cookie when the script runs for the first time, the $ _ COOKIE ["vegetable"] variable will not be created at this time. Because a cookie is read only when the browser sends it to the server, it can be read only when the user re-accesses a page in the domain.
To delete a cookie, you only need to call setcookies () with the cookie name parameter ():
Setcookie ("vegetable ");
However, this method does not always work and cannot depend on it. On the contrary, it is safest to delete a cookie and set the cookie with a specified expiration time:
Setcookie ("vegetable", "", time ()-60, "/", "yourdomain.com", 0 );
Make sure that the path, domain, and security parameters passed to setcookie () are the same as those used when the cookie is initially set.

3. Overview of session functions

When a visitor accesses a page that supports sessions, either a new identifier is assigned or the user is re-associated with an identifier that has been created for the previous access. Any variables associated with the SESSION can be used by the $ _ SESSION Super global variable for your code.
Session status is usually stored in a temporary file, although you can use a function named session_set_save_handler () to implement database storage.

4. start a session

The code is as follows:

<? Php
Session_start ();
Echo"

Your session ID is ". session_id ()."

";
?>


5. use session variables

Accessing a unique session identifier in each PHP document is only the beginning of the session function. After a SESSION is started, we can store any number of variables in the Super global variable $ _ SESSION and access them on any page that supports sessions.

The following program adds two variables to the Super global variable $ _ SESSION:

The code is as follows:

<? Php
Session_start ();
$ _ SESSION ["product1"] = "Sonic Screwdriver ";
$ _ SESSION ["product2"] = "HAL 2000 ";
Echo "The products have been registered .";
?>


Before a user moves to a new page, the magic of the above program will not be reflected. The following program creates a separate PHP script, which accesses the variables stored in the Super global variable $ _ SESSION.

The code is as follows:

<? Php
Session_start ();
Echo "Your chosen products are :";
Echo"

    ";
    Echo"
  • ". $ _ SESSION [" product1 "]."
  • ";
    Echo"
  • ". $ _ SESSION [" product2 "]."
  • ";
    Echo"
";
?>


The following program list creates a form that allows one user to select multiple products. We can use session variables to create a basic shopping cart.
Arraysession. php:

The code is as follows:

<? Php
Session_start ();
?>


Storing an array with a session


Product Choice Page
<? Php
If (isset ($ _ POST ["form_products"]) {
If (! Empty ($ _ SESSION ["products"]) {
$ Products = array_unique (
Array_merge (unserialize ($ _ SESSION ["products"]),
$ _ POST ["form_produces"]);
}
Else
{
$ _ SESSION ["products"] = serialize ($ _ POST ["form_products"]);
}
Echo"

Your products have been registered!

";
}
?>

Go to content page





Session1.php:

The code is as follows:

<? Php
/*
* Created on 2011-1-19
*
* To change the template for this generated file go
* Window-Preferences-PHPeclipse-PHP-Code Templates
*/
Session_start ();
?>


Accessing session variables


Content Page
<? Php
If (isset ($ _ SESSION ["products"]) {
Echo"Your cart:

    ";
    Foreach (unserialize ($ _ SESSION ["products"]) as $ p ){
    Echo"
  1. ". $ P ."
  2. ";
    }
    Echo"
";
}
?>

Return to product choice page




6. pass the session ID in the query string

7. destroy sessions and reset variables

8. Use sessions in an environment with registered users

I hope this article will help you with php programming.

Examples in this article describes how php uses cookies and user sessions. Share it with you for your reference. Specific analysis...

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.