PHP Session Processing

Source: Internet
Author: User
Tags echo date php session
Session is divided into two parts, session space is stored on the server side, open the ID of the space in the client's cookie, if the client shuts down the cookie,session can not be used normally.
Source: http://wsiyu.com/read.php?tid=526
The Chinese translation of the session is called "conversation", its original meaning refers to the beginning and end of a series of actions/messages, such as phone calls from the pick up the telephone to hang up the phone in the middle of a series of processes can be called a session. At present, the community's understanding of the session is very confusing: sometimes we can see the words "during a browser session, ...", where the session is opened from a browser window to close this period, you can also see "User (client) during a session," the word, It may refer to a series of actions by a user (typically a series of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout), but sometimes it may simply mean a connection; the differences can only be inferred by context.

However, when the term session is associated with a network protocol, it often implies a "connection-oriented" and/or "hold State" two meanings, "connection-oriented" refers to the communication between the two parties before the communication to establish a channel of communication, such as the telephone, until the other side of the phone communication to start. "Hold state" means that the party of communication can associate a series of messages, so that the message can be interdependent, such as a waiter can recognize the return of the old customers and remember the last time the customer owed a money in the store. Examples of this type are "a TCP session" or "a POP3 session."

Given that this confusion is immutable, it is difficult to define the session in a uniform standard. When reading the session, we can only infer the understanding by the context. However, we can understand this: for example, we call, from the moment we dial to hang up the phone, because the phone has been kept connected, so the status of this connection is called the session. It is a public variable that always exists during the interaction between the visitor and the entire website, and the session variable is used to ensure the data is correct and secure when the client does not support cookies. Visitors to the site are assigned a unique identifier, the so-called session ID. It is either stored on the client's cookie or passed through the URL.

The invention of the session fills the limits of the HTTP protocol: the HTTP protocol is considered a stateless protocol and the user's browsing state is not known, and the server loses contact with the browser after it has completed its response on the service side. This is consistent with the HTTP protocol's original purpose, and the client simply requests to download certain files to the server, neither the client nor the server need to record each other's past behavior, each request is independent, Like the relationship between a customer and a vending machine or an ordinary (non-membership) hypermarket.

Therefore, the session (the cookie is another solution) records the user's information, so that the user again in this identity to the Web server to make a request for confirmation. The invention of the session allows a user to save his or her information while switching between multiple pages. Web programmers have this experience, the variables on each page cannot be used on the next page (although Form,url can also be implemented, but this is a very undesirable approach), and the variables registered in the session can be used as global variables.

So what's the use of the session? When shopping on the Internet, everyone has used a shopping cart, you can always add your purchases to the shopping cart, and then go to the cashier checkout. Throughout the process, the shopping cart has been playing the role of temporary storage of the selected products, using it to track the user's activity on the site, this is the role of the session, it can be used for user authentication, program status records, the parameters of the page transfer and so on.

In the implementation of the session using cookie technology, session will save a session_id (session number) in the client cookie, the server side to save other session variables, such as Session_name and so on. When the user requests the server also sends the session_id to the server, through session_id extracts the variable which is saved on the server side, can identify the user is who. It is also not difficult to understand why the session sometimes fails.

When the client disables cookies (click "Tools" in IE?). "Internet Options", click "Security" in the Pop-up dialog box. Custom level item, set allow each dialog cookie to disabled, session_id will not be delivered, and the session is invalidated. However PHP5 on the Linux/unix platform can automatically check the cookie status, if the client is set to disable, the system automatically attaches the session_id to the URL to pass. The Windows host does not have this feature.

Session common functions and usage?

Session_Start (): Starts a session or returns a session that already exists.

Description: This function has no parameters and the return value is true. If you use a cookie-based session (Cookie-based sessions), the browser cannot have any output before using session_start (), otherwise the following error will occur: Warning:cannot send Session Cache Limiter-headers already sent (output started At/usr/local/apache/htdocs/cga/member/1.php:2) .....

You can start session.auto_start=1 in php.ini so that you don't need to call session_start () before you use the session. However, there are some restrictions on enabling this option, and if you do enable Session.auto_start, you cannot put an object into a session because the class definition must be loaded before starting the session to rebuild the object in the session.

All registered variables will be serialized after the request is finished. A variable that has been registered but not defined is marked as undefined. In subsequent accesses, these variables are not defined by the session module unless they are defined later by the user.

Warning: Some types of data cannot be serialized and therefore cannot be saved in the session. Includes a resource variable or an object that has a circular reference (that is, an object passes a reference to itself to another object).

Register Session Variables:

PHP5 uses $_session[' xxx ']=xxx to register the SESSION global variable.

It is similar to the Get,post,cookie method.

Note: Session_register (), Session_unregister, session_is_registered is no longer used under PHP5, unless PHP.ini is set to on in Register_globle, However, for security reasons, it is highly recommended to close register_globle. Http_session_vars also do not advocate the use of, the official proposed to replace it with $_session.

For example:

page1.php <?php session_start (); You must call this function before using the session.

$_session[' name ']= "I am a black tornado Li Kui!";

Register a SESSION variable $_session[' passwd ']= "Mynameislikui";

$_session[' time ']=time ();

Echo ' <br/><a href= ' page2.php ' > Pass the session </a> ' through a cookie;

If the client supports cookies, you can pass the session to the next page through the link.

Echo ' <br/><a href= ' page2.php? '. Sid. ' > Pass the session </a> ' through the URL;

This method is used to pass the session when the client does not support cookies. ? >

page2.php <?php session_start (); echo $_session[' name '];

echo $_session[' passwd '];

echo Date (' Y m D h:i:s ', $_session[' time ');

Echo ' <br/><a href= ' page1.php ' > Back to the Mountain page </a> ';? '

There are two ways of passing a session Id:cookie URL parameter

The session module supports both of these methods. Cookies are more optimized, but they also provide alternative methods because they are not always available. The second method embeds the session ID directly in the middle of the URL. PHP can transparently convert connections. Unless you are using PHP 4.2 or later, you need to manually activate PHP when compiling. Under Unix, configure the options with--enable-trans-sid. If both this configuration option and the Run-time option Session.use_trans_sid are activated (modify php.ini), the relative URI is automatically modified to contain the session ID.

session_id session_id () is used to set or get the current session_id.

The php5 can either use session_id (), or the session_id and Session_name of the current session can be obtained by appending the SID on the URL.

If session_id () has a specified value, the current session_id value will be replaced. The session must be started before using the function: session_start (); When we use session cookies, if a session_id () value is specified, each boot session_start () will send a cookie value to the client. Regardless of whether the current session_id is equal to the specified value.

SESSION_ID () returns the current session_id () If no value is specified, or an empty string if the current session is not started.

Check to see if the session exists?

In previous versions of PHP, Session_is_register () was commonly used to check if a session exists, and if you use $_session[' XXX ']=xxx to register a conversation variable, session_is_register () function no longer works. You can use Isset ($_session[' xxx ') to replace it.

Change session_id session_regenerate_id () The change succeeds returns True, and false returns if it fails.

Use this function to change the session_id for the current session without changing the other information for the current session.

For example:

<?php

Session_Start ();

$old _sessionid = session_id ();

SESSION_REGENERATE_ID ();

$new _sessionid = session_id ();

echo "Original SessionID: $old _sessionid<br/>";

echo "New SessionID: $new _sessionid<br/>";

echo "<pre>"; Print_r ($_session);

echo "</pre>";

? >

Session_name () returns the name of the current session or changes the name of the current session.

If you want to change the name of the current session, you must call the function before Session_Start ().

Note: Session_name cannot consist of numbers only, it contains at least one letter. Otherwise, a new session ID will be generated at every moment of the day.

Example of Session renaming:

<?php

$previous _name = Session_name ("WebSiteID");

echo "New session Name: $previous _name<br/>";

? >

How do I delete a session?

1, unset ($_session[' xxx ']) delete a single session,unset ($_session[' xxx ') to unregister a registered SESSION variable. Its effect is the same as Session_unregister (). Session_unregister () is no longer used in PHP5 and can be limbo.

Unset ($_session) This function must not be used, it will destroy the global variable $_session, and there is no viable way to restore it. Users can no longer register $_session variables.

2, $_session=array () delete more than one SESSION

3. Session_destroy () ends the current session and empties all resources in the session. The function does not unset (releases) the global variables associated with the current session (GlobalVariables), nor does it delete the client's session cookie. PHP's default session is cookie-based, and if you want to delete a cookie, you must use the Setcookie () function.

Return value: A Boolean value.

Function Description: This function ends the current session, this function has no parameters and the return value is True

Session_unset () If $_session is used, the function no longer works. Since PHP5 is bound to use $_session, this function can be limbo.

The following is the official PHP case to delete the session:

<?php//Initialize session. Session_Start ();

/*** Delete all the session variables: Unset ($_session[xxx]) can also be deleted individually. ****/

$_session = Array ();

/*** Delete the Sessin ID. Because the session is cookie-based by default, use Setcookie to delete the cookie.***/that contains the session ID.

if (Isset ($_cookie[session_name ()))) {Setcookie (Session_name (), ", Time ()-42000, '/');}

Finally, the session is completely destroyed. Session_destroy ();

? >

Thus we can draw the steps to delete the session:

①session_start ()

②$_session=array ()/unset ($_session[' xxx ')

③session_destroy ()

Session security:

The session module cannot guarantee that the information stored in the session can only be seen by the user who created the session. Depending on the data they hold, more action is needed to proactively protect the integrity of the session.

Evaluating the data that is carried in the session and enforcing additional protections usually costs a lot and reduces the user's convenience. For example, if you want to protect a user from a simple social policy (note: The session ID shown in the URL will be seen on the computer screen, or by another website via HTTP Referer), then session.use_only_cookies should be enabled. In this case, the client must enable cookies unconditionally or the session will not work.

There are several ways to leak an existing session ID to a third party. The leaked session ID enables a third party to access all resources associated with the specified ID. First, the URL carries the session ID. If you connect to an external site, a URL that contains a session ID may be present in the Referer log of the external site. Second, a more aggressive attacker might listen for packets on a network segment. If unencrypted, the session ID flows through the network in clear text mode. The solution to this is to enforce SSL on the server and force the user to use it.

By default, all data related to a particular session is stored in a file in the directory specified by the INI option Session.save_path. A file is created for each session (regardless of whether there is data associated with the session). This is because a file is created every time a session is opened, regardless of whether or not there is data written to the file. Note Because of the limitations of working with file systems, this behavior has a side effect that could result in a user-customized session processor (for example, a database) losing a session that does not store data. The functions described above will be used, but there are also some functions about the session:

Session_encode

function function: sesssion information encoding

Function prototype: string session_encode (void);

return value: String

Function Description: The returned string contains the names and values of the variables in the global variable, in the form of: A|s:12: "It is a test\"; C|s:4: "Lala"; A is the variable name s:12 represents the value of variable a "it is a test length is a semicolon between 12 variables"; Separated.

Session_decode

function function: sesssion information decoding

Function prototype: Boolean Session_decode (String data)

Return Value: Boolean value

Function Description: This function can decode session information, and success returns logical value TRUE

PHP5 no longer uses session_id, but instead turns it into a constant SID and is saved in a cookie. If the client is disabled, cookie,php automatically passes the SID via the URL automatically, with the condition that Session.use_trans_sid = 1 is set in php.ini. This is fine even if the client has disabled cookies.

Use Strip_tags () to output SIDS to avoid XSS-related attacks.

Session cross-page delivery problem:

There are three things to consider in session cross-page delivery:

The ① client has disabled cookies.

② browser problems, temporarily unable to access cookies

Session.use_trans_sid = 0 in ③php.ini or the--ENABLE-TRANS-SID option is not open at compile time why is that?

Let's explain why:

The session file is divided into two parts: the session variable is saved on the server side (by default, the session is stored as a file), and the session ID is saved as a cookie on the client. (Note: The session is cookie-based by default).

When the user's browser requests the server, it also sends a cookie containing the session ID (by default). The server comes to the user's file based on the session ID provided by the client, which is the value of the session variable stored on the server side. In fact, the session ID can use the client's cookie or the query_string of the Http1.1 protocol (that is, the "?" of the URL being accessed.) Later) to the server, and then the server reads the Session Directory ....

That is, the session ID is the ID that gets the session variable stored on the service. When the Code session_start (), run, on the server generated a session file, followed by the only corresponding to a session ID, define the session variable to be stored in a certain form in the session file just generated. The session ID allows you to remove the defined variable. After the spread, in order to use the session, you must also execute session_start (); A session file will be generated, corresponding to the session ID, with this session The ID is not the variable in the first session file mentioned above, because the session ID is not the "key" to open it. If the Session_Start (), preceded by the code session_id ($session ID), will not generate a new session file, directly read the session file corresponding to this ID.

The session in PHP uses the client's cookie to save the session ID by default, so it will affect the session when there is a problem with the client's cookie.

It is important to note that the session does not necessarily have to rely on cookies, which is a clever place for the session compared to cookies. When the client's cookie is disabled or there is a problem, PHP automatically attaches the session ID to the URL, so that the session ID can be used across the page to use the session variable. But this attachment also has certain conditions,

One: "Session.use_trans_sid in php.ini = 1 or open--enable-trans-sid option at compile time"; second: the server running PHP must be a unix/linux system and Windows does not have this feature. Having understood the above, we can draw three ways to solve the problem of cross-page transmission:

1. Set session.use_trans_sid = 1 in php.ini or open the--ENABLE-TRANS-SID option at compile time to have PHP automatically pass the session ID across pages.

2, manually pass the URL value, hide the form passed session ID.

3, file, database and other forms to save session_id, in the process of cross-page manual call.

The following examples illustrate:

First case:

page1.php

<?php

Session_Start ();

$_session[' var1 ']= "People's Republic of China";

$url = "<a Href=". " \ "S2.php\" > next page </a> "; echo $url;

? >

page2.php

<?php

Session_Start ();

echo "passes the value of the SESSION variable var1:". $_session[' var1 ');

? >

Running the above code, in case the client cookie is normal, should be able to get the result "People's Republic of China".

Now you manually shut down the client's cookie and run it, you may not get the result. If you don't get the results, then "set Session.use_trans_sid = 1 in php.ini" or "open--enable-trans-sid option at compile time" and get results "People's Republic of China"

The second way:

s1.php

<?php

Session_Start ();

$_session[' var1 ']= "People's Republic of China";

$SN = session_id ();

$url = "<a Href=". " \ "S2.php?s=". $sn. " \ "> next page </a>";

PHP5 defines a constant SID to represent session_id (), $url can also be written $url= ' <a Href= ' page2.php? '. Sid. ' "next page </a> '; echo $url;

? >

s2.php

<?php

session_id ($_get[' s ');

Session_Start ();

echo "passes the value of the SESSION variable var1:". $_session[' var1 ');

? >

The Third Way:

Login.html

! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >



<title> Login </title>

<meta http-equiv= "Content-type" content= "text/html; charset=?????? " >


<body> Please log in:

<form name= "Login" method= "POST" action= "mylogin1.php" >

User name: <input type= "text" name= "name" >

<br>

Password

<input type= "password" name= "pass"

<br>

<input type= "Submit" value= "Login" >

</form>

</body>


mylogin1.php

<?php

$name =$_post[' name '];

$pass =$_post[' pass ';

if (! $name | |! $pass)

{echo "username or password is blank, please <a Href=\" login.html\ "> re-login </a>";

Die ();

}

if (! ( $name = = "Laogong" && $pass = = "123"))

{echo "username or password is incorrect, please <a Href=\" login.html\ "> re-login </a>"; Die ();}

Registered users

Ob_start ();

Session_Start ();

$_session[' user ']= $name;

$psid =session_id (); $FP =fopen ("E:\\tmp\\phpsid.txt", "w+");

Fwrite ($fp, $psid);

Fclose ($FP); Authentication successful, related operations

echo "Logged in <br>";

echo "<a Href=\" mylogin2.php\ "> next page </a>";

? >


mylogin2.php

<?php

$FP =fopen ("E:\\tmp\\phpsid.txt", "R");

$sid =fread ($FP, 1024); Fclose ($FP);

session_id ($SID);

Session_Start ();

if (Isset ($_session[' user ") && $_session[' user ']=" Laogong ")

{

echo "Logged in!"; } else {//successful login for related actions echo "not logged in, not authorized to access";

echo "Please <a Href=\" login.html\ "> login </a> after browsing";

Die ();

}

? >
  • Related Article

    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.