Dynamic Web page Common technology: Follow variables with PHP (cookies and session)

Source: Internet
Author: User
Tags exit file system variables range valid domain client in domain

In many cases, we need to track the activities of our viewers throughout the site, automatic or semi-automatic identification of their identities (that is, the usual web site landing functions), at this time, we often use a set of variables to "follow" visitors. There are a number of ways to implement a variable "follow", compared with cookies and sessions. Here we use the current very popular PHP for you to explain their use.

A. Use of cookies

Cookies are information that the Web site keeps in the browser's client, which means that variables stored in the visitor's machine are typically sent to the client with HTTP hair. After the cookie is in effect and before the expiration, each time the customer makes a page request, the cookie is sent to the server, as long as we handle it appropriately, we can implement the variable "follow".

1. Set a cookie variable

To set a cookie variable, PHP uses the following function:

int setcookie(string name, string value, int expire, string path, string domain, int secure);

Where name is the cookie variable name identifier, you can use it to refer to the cookie variable in PHP as if you were using a normal variable name. Value is the initial value of the cookie variable, expire represents the valid time for the cookie variable, path is the associated path for the cookie variable, and the Web site that represents the cookie variable in domain, and secure is valid for the secure transmission of HTTPS.

For example we want to set a variable username, its value is the string "Bluewind", we can write code like this:

setcookie (“username”,“bluewind”); //这两个参数是setcookie必要的。

We also want to set a valid time for this variable to limit the operation timeout, such as 10 minutes:

setcookie (“username”,“bluewind”, 600000); //有效时间的单位是毫秒。

Note: Setcookie, like the header function, needs to be placed before any statements that can be output to the client.

2. Destroy a variable

Destroying a cookie variable simply sets its value to empty (""), and if you want to destroy the variable above, just write it again:

setcookie (“username” ,“”);

It's OK. This is often used as a safe exit.

3. Valid range and lifetime of cookies

The valid range of cookies (that is, you can get this cookie variable in this range of pages) defaults to the directory and its subdirectories, and of course you can modify it with Setcookie's path and domain parameters. If you do not set the cookie expire (see 1). Set an example in a cookie variable, then when you leave the Site page, the cookie is also automatically destroyed.

Http://www.netscape.com/newsref/std/cookie_spec.html is the complete introductory information provided by the cookie creator Netscape.

Second, the use of the session

Session variables, which are conversational-level variables, are public variables that are present throughout the process of interacting with the site. When the client does not support the possibility of not supporting cookies (such as Lynx under Linux ...). Oh, miserable point), we need to use the session variable in order to ensure the correct data security. The session is implemented differently in various web language languages, and PHP has been supporting it since 4.0. First, let's take a look at a simple example:

test.php ----------- <?session_start(); session_register(var); //注册变量var$var="这是SESSION变量的值"; //var变量已经被作为session变量 ?>test1.php ------ <?session_start(); session_register(var); echo $var; //输出:“这是SESSION变量的值”?>

1. Initial session

If the PHP settings are not opened automatically, you need to initialize a session using the Session_Start () function, which is used as follows:

: boolean session_start(void);

Its role is to initialize a new session, if the customer has been in sessions, then connect the original. This function has no arguments and the return value is true.

2. Register a variable in session

The variables you want to save in session must be registered with the following function:

boolean session_register(string name);

This function adds a variable to the global variable to the current session. The parameter name is the name of the variable you want to join. Returns a true value if successful.

You can then assign it directly using the variable name, and the value will be saved.

3, using the value of the session variable

As shown in the example above, you can use the session variable directly if you repeat two steps (except assignment) on the new page.

4, the session of the destruction

If you just want to log off a variable instead of destroying the entire variable, you need to use a function:

boolean session_unregister(string name);

The usage is simple, and the parameter name is the name of the variable you want to delete. Returns a true value if successful.

However, if you want to "destroy" the session variable, such as a safe exit or something, use a function:

boolean session_destroy(void);

This function ends the current session. This function has no arguments and the return value is true.

5. Other useful session functions

A, check whether the variable is registered

boolean session_is_registered(string name);

This function checks to see if the specified variable registration is already in the current session. The parameter name is the name of the variable you want to check. Returns a true value if successful.

b, to the registration variable to NULL

This function can place all of the session variables that are of course registered as NULL. Note that it is not unregister, but also different from destroy. The following example shows a good description of this function.

<?php session_register('a','b','c'); //auto-session-start $a=1; $b=2; $c=3; session_unregister('a'); //unregistrered $a echo "A: $a - reg:".session_is_registered('a')." ";// but the global $a remains session_unset(); // unsets $b und $c echo "B:$b - reg:".session_is_registered('b')." "; // the registration remains ! echo "C:$c - reg:".session_is_registered('c')." "; echo session_encode(); ?> 输出: A: 1 - reg: B: - reg:1 C: - reg:1 !b|!c|

c, customize your own session processing method

This function can define the Save function (open, close, write, and so on) of the user-level session. This function is useful, for example, when we want to save a session in a local database. By default, each session is stored in a separate file in the system's temporary directory (for example,/tmp in a UNIX system). This fits or doesn't fit, depending on your needs. For example, if your PHP-enabled Web server is distributed across different machines, you cannot easily share the session between them (and, of course, you can also save Sessions to NFS shares). Another potential problem is that thousands of or millions of session files on your machine make your file system fragmented. Note: This function appears only after the 4.0B4 version. Before using this function, you must first configure the php.ini file, Session.save_hadler=user, otherwise, Session_set_save_handler () will not take effect.

Also, according to my tests, if you want this session to be used across pages, add your own functions and Session_set_save_handler to every script file that you use in the session, so the best way is to make a separate file, Include in every script that will use session.

The following example provides a basic session save method, similar to the default files method. If you want to use the database to achieve, this is also very easy to do.

Example:session_set_save_handler () Example <?php function open ($save _path, $session _name) {Global $sess _save_path, $sess _session_name; $sess _save_path = $save _path; $sess _session_name = $session _name; return (true); function Close () {return (true);} function read ($id) {global $sess _save_path, $sess _session_name; $sess _file = "$sess _save_path/sess_$id "; if ($fp = @fopen ($sess _file, "R")) {$sess _data = fread ($fp, FileSize ($sess _file)); return ($sess _data);} else {return ("" ); } function Write ($id, $sess _data) {global $sess _save_path, $sess _session_name; $sess _file = "$sess _save_path/sess_$id" ; if ($fp = @fopen ($sess _file, "W")) {return (fwrite ($fp, $sess _data));} else {return (false);}} function Destroy ($id) {global $sess _save_path, $sess _session_name $sess _file = "$sess _save_path/sess_$id"; Unlink ($sess _file)); }/********************************************* * Warning-you'll need to implement some * * sort of garbage collect Ion routine here. * * ******/function GC ($maxlifetime) {return true;} session_set_save_handler ("Open", " Close "," read "," write "," Destroy "," GC "); Session_Start ();  Proceed to using sessions normally//Now you can use the session as usual.?>


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.