PHP uses cookie implementation and user session methods, Phpcookie implementation session _php Tutorial

Source: Internet
Author: User
Tags php language set cookie

PHP uses cookie implementation and user session method, Phpcookie implementation session


The examples in this article describe how PHP uses cookie implementations and user sessions. Share to everyone for your reference. The specific analysis is as follows:

PHP contains a number of functions that can be used to manage and record user information, including simple cookies and a full range of user sessions. The session uses the PHP language built-in technology to make the save state as simple as referencing a hyper-global variable.

1.Cookie Introduction

We can use cookies together with PHP scripts to store some small information about the user. A Cookie is a small amount of data stored by a user's browser, which is consistent with a request from a server or script. Through a user's browser, a single host can request to save 20 cookies. Each cookie contains a name, a value and an expiration date, as well as host and path information. The size limit for a single cookie is 4KB.

After the cookie is set, only the requesting host can read the data, which guarantees that the user's privacy will be respected. In addition, the user can configure his or her browser to accept or reject all requests for cookies. Therefore, cookies should be used moderately and should not be relied upon as a basic element in an environment where there is no design implementation to warn the user.

If the Web browser is configured to store cookies, it will keep cookie-based information until the expiration date. If the user browses to the cookie-compliant path and any page of the domain using the browser, it will re-send the cookie to the server. Later, a PHP script can access the cookie, the cookie in the environment variable Http_cookie, or as part of the $COOKIE Super global variable, we can access them in 3 ways:
Copy the Code code 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 then included in the header portion of the server response. Since the header will be sent automatically for you, the header () must be called before sending it to the browser's output.
Copy the Code Code as follows: Head ("Set Cookie:vegetable=artichoke; expires=tue,07-mar-06 14:39:58 gmt;path=/;d omain=yourmain.com ");
Although there is no difficulty, this method of setting cookies requires us to write a function to construct the header string. Formatting dates and URL-coding a name/value pair, like this example, is not particularly difficult, but it is a repetitive task because PHP provides a function to do this, which is Setcookie ().

The Setcookie () function does the same thing as its name shows, and it outputs a Set-cookie header. Therefore, it should be called before any other content is sent to the browser. This function accepts the cookie name, cookie value, expiration date of the UNIX timestamp format, path, domain, and an integer whose value is set to 1 if the cookie is sent only through a secure connection. All parameters of this function are optional except for the first parameter.
Copy the Code code 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 your first visit.

" ;
}
?>
Even if we set the cookie at the first run of the script, the $_cookie["vegetable" variable is not created at this time. Since the browser will only read a cookie when it is sent to the server, we will not be able to read it until the user re-accesses a page in the domain.
Formally, to delete a cookie, you only need to invoke the Setcookies () with the cookie name parameter:
Setcookie ("vegetable");
However, this approach does not always work and cannot be relied upon. Instead, it is safest to delete a cookie and set a cookie using a time that determines that it has expired:
Setcookie ("Vegetable", "", Time () -60, "/", "yourdomain.com", 0);
Also make sure to pass to Setcookie () the same path, domain, and security parameters that were used when the cookie was originally set.

3. Overview of Session Functions

When a guest accesses a page that supports a session, either assigns a new identifier, or the user is re-associated with an identifier that was already established by the previous access. Any variables that are already associated with a session are available to your code through the $_session Super global variable.
Session state is typically stored in a temporary file, although you can use a function called Session_set_save_handler () to implement database storage.

4. Start a session
Copy the Code code as follows: <?php
Session_Start ();
echo "

Your session ID is ". SESSION_ID (). "

" ;
?>
5. Using Session Variables

Accessing a unique session identifier in every PHP document is just the beginning of the session feature. When a session is started, we can store any number of variables in the hyper-global variable $_session and then access them on any page that supports the session.

The following program adds two variables to the hyper-global variable $_session:
Copy the Code code as follows: <?php
Session_Start ();
$_session ["product1"] = "Sonic screwdriver";
$_session ["product2"] = "HAL 2000";
echo "The products has been registered.";
?>
The magic of the program doesn't show up until the user moves to a new page. The following program creates a separate PHP script that accesses variables stored in the Hyper-global variable $_session.
Copy the Code code as follows: <?php
Session_Start ();
echo "Your chosen products is:";
echo "

      " ;
      echo "
    • " . $_session ["Product1"]. "
    • " ;
      echo "
    • " . $_session ["Product2"]. "
    • " ;
      echo "
" ;
?>
The following list of programs creates a form that allows one user to select multiple products. We can use session variables to create a basic shopping cart.
arraysession.php:
Copy CodeThe code is as follows: <?php
Session_Start ();
?>


<title>Storing an array with a session</title>


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 has been registered!

" ;
}
?>

Go to content page





session1.php:
Copy CodeThe code is as follows: <?php
/*
* Created on 2011-1-19
*
* To change the template for this generated file go to
* Window-preferences-phpeclipse-php-code Templates
*/
Session_Start ();
?>


<title>accessing Session Variables</title>


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. Passing the session ID in the query string

7. Destroying sessions and resetting variables

8. Using sessions in an environment with registered users

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/945701.html www.bkjia.com true http://www.bkjia.com/PHPjc/945701.html techarticle PHP uses cookie implementation and user session methods, Phpcookie implementation session This article describes how PHP uses cookie implementations and user sessions. Share to everyone 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.