About session usage in PHP

Source: Internet
Author: User
Tags echo date session id

What is a session?

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.

Common functions and usage of Session

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

View Plaincopy to Clipboardprint?

Session_Start (); You must call this function before using the session.

$_session[' name ']= "Nowamagic"; Register a Session variable

$_session[' passwd ']= "hellomagic";

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

Echo '
Pass the session through a cookie; If the client supports cookies, you can pass the session to the next page through the link.

Echo '
Pass the session through the URL;//The client uses this method to pass the session when it does not support cookies.

?>

page2.php

View Plaincopy to Clipboardprint?

Session_Start ();

echo $_session[' name ']; //

echo $_session[' passwd ']; //

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

Echo '
Return to the Mountain page ';

?>

There are two ways of passing a session ID:

One is a cookie and the other is a 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 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 () returns True if the change succeeds, and false 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:

View Plaincopy to Clipboardprint?

Session_Start ();

$old _sessionid = session_id ();

SESSION_REGENERATE_ID ();

$new _sessionid = session_id ();

echo "Original SessionID: $old _sessionid
";

echo "New SessionID: $new _sessionid
";

Echo

";  

Print_r ($_session);

Echo

";

?>

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:

View Plaincopy to Clipboardprint?

$previous _name = Session_name ("WebSiteID");

echo "New session Name: $previous _name";

?>

How to delete a session

unset ($_session[' xxx ']) deletes 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.

$_session=array () Delete more than one SESSION

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:

View Plaincopy to Clipboardprint?

Initializes the 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 function Description: This function can decode session information, Successful returns the 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.

There is a problem with the browser, temporarily unable to access cookies

Session.use_trans_sid = 0 in php.ini or--ENABLE-TRANS-SID option is not turned on 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 (); When running, a session file is generated on the server, and the only corresponding session ID is generated, defining the session variable to be stored in a certain form in the session file that was just generated. The session ID allows you to remove the defined variable. After the cross-page, in order to use the session, you must execute session_start (); A session file will be generated, corresponding to the session ID, with this session ID is not the first mentioned in the previous session file in the change Because the session ID is not the "key" that opens it. If in session_start (); Previously added 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 kind of attachment also has certain condition, 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, Windows does not have this feature.

Having understood the above, we can draw three ways to solve the problem of cross-page transmission:

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.

Pass the session ID manually via URL pass-through, hidden form.

Save the session_id in the form of files, databases, etc., and call them manually during the cross-page process.

The following examples illustrate:

First case:

page1.php

View Plaincopy to Clipboardprint?

Session_Start ();

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

$url = "Next page";

echo $url;

?>

page2.php

View Plaincopy to Clipboardprint?

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 the--ENABLE-TRANS-SID option at compile time" and get the result "People's Republic of China".

The second way:

s1.php

View Plaincopy to Clipboardprint?

Session_Start ();

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

$SN = session_id ();

PHP5 defines a constant SID to represent session_id (), $url can also be written $url= ' next page ';

$url = "Next page";

echo $url;

?>

s2.php

View Plaincopy to Clipboardprint?

session_id ($_get[' s ');

Session_Start ();

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

?>

The Third Way:

Login.html

View Plaincopy to Clipboardprint?

Login

Please login:

mylogin1.php

$name =$_post[' name '];

$pass =$_post[' pass ';

if (! $name | |! $pass) {

echo "User name or password is blank, please login again";

Die ();

}

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

echo "username or password is incorrect, please login again";

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
";

echo "Next page";

?>

mylogin2.php

View Plaincopy to Clipboardprint?

$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 operations

echo "Not logged in, not authorized to access";

echo "Please login and browse";

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.