Come with me. Use and analysis of php5:session conversation

Source: Internet
Author: User
Tags definition class definition empty file system function prototype functions session id variables

The Chinese translation of the session is called "conversation", whose meaning is a series of actions/messages from the beginning to the end, such as calling from the phone to the telephone to hang up the phone in the middle of a series of processes can be called a sessions. At present, the understanding of the session in the community is very confusing: sometimes we can see the words "during a browser session, ...", where the conversation is from a browser window open to the end of this period, you can also see the "User (client) during a session" such a sentence, It may refer to a series of actions by a user (typically a sequence of actions related to a specific purpose, such as a process of online shopping from login to purchase to checkout; however, sometimes it may just be a connection; the difference can only be inferred by context.)

However, when the term session is associated with a network protocol, it also tends to imply 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 communication channel, such as telephone, until the other side of the telephone communication to start. "Staying state" means that one side of the communication can associate a series of messages so that the messages can be interdependent, such as a waiter who can recognize the old customer again and remember that the last time the customer owed the store a dollar. Examples in this category are "one TCP session" or "one POP3 session".

Given that this confusion is immutable, it is difficult to define a uniform standard for the session to be defined. And in reading the session-related material, we can only infer the understanding by context. However, we can understand this: for example, we call, from the moment of dialing to hang up the phone, because the phone is always connected to the state, so the status of this switch is called session. It is the visitor and the entire website interaction process always exists the public variable, when the client does not support the cookie, in order to guarantee the data to be correct, the security, uses the session variable. Visitors to the site are assigned a unique identifier, known as the session ID. It is either stored on the client's cookie or passed through the URL.

The session's invention fills in the limitations of the HTTP protocol: the HTTP protocol is considered a stateless protocol, and the user's browsing status is not known, and the server loses contact with the browser when it completes its response on the service side. This is consistent with the HTTP protocol's original purpose, the client simply needs to download some files to the server, whether the client or the server does not 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-member) hypermarket.

As a result, the user's information is logged by session (cookie is an alternative solution) for the user to confirm when requesting the Web server again in this capacity. The invention of the session allows a user to save his information when switching between multiple pages. Website programmers have the experience that the variables on each page can not be used on the next page (although Form,url can also be implemented, but this is a very unsatisfactory way), and session of the registered variables can be used as a global variable.

So what is the use of the session? When shopping on the Internet, everyone has used a shopping cart, you can always add the goods you buy to the shopping cart, and finally go to the cashier checkout. Throughout the process, the shopping cart has been playing the role of temporary storage of selected goods, using it to track the activities of users on the site, this is the role of the session, it can be used for user identity authentication, program status records, transfer between the parameters of the page.

In the implementation of the session, cookie technology is used to save a cookie containing the session_id on the client, and to save additional session variables on the server side, such as Session_name and so on. When the user requests the server also sends the SESSION_ID together to the server, through session_id extracts is saved on the server side the variable, 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", "Allow each dialog cookie" to be disabled), SESSION_ID will not be delivered, and the session fails. However, PHP5 can automatically check the cookie status on the Linux/unix platform, and if the client is set to disable, the system automatically attaches the session_id to the URL for delivery. The Windows host does not have this capability.

   Session common function and usage?

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

Note: 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 (), or the following error occurs:

Warning:cannot Send session Cache Limiter-headers already sent (output started AT/USR/LOCAL/APACHE/HTDOCS/CGA/MEMBER/1 . php:2) ......

You can start the session.auto_start=1 in php.ini so you don't need to invoke session_start () every time you use the session. However, there are some limitations on enabling this option, and if Session.auto_start is enabled, you cannot put the object into a session because the class definition must be loaded before the session is started to rebuild the object in the session.

All registered variables are serialized after the end of the request. A variable that is registered but undefined is marked as undefined. These variables are also not defined by the session module in subsequent accesses, unless they are defined later by the user.

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

   Register Session variable:

PHP5 registers the session global variable with the $_session[' xxx ']=xxx. It is similar to the way Get,post,cookie is used.

Note: Session_register (), Session_unregister, session_is_registered are no longer used under PHP5 unless the php.ini is set to on in Register_globle, However, for security reasons, it is strongly recommended that register_globle be closed. Http_session_vars also does not advocate the use, the official proposal uses $_session to replace it. For example:

page1.php

<?php
Session_Start (); You must call this function before you use session.
$_session[' name ']= "I am the black whirlwind likui!"; Register a Session variable
$_session[' passwd ']= "Mynameislikui";
$_session[' time ']=time ();
Echo ' <br/><a href= ' page2.php ' passes 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. ' "to pass the session through the URL, the session </a> ';//The client does not support cookies, use this method to pass the session.
? >
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" and returns to the Mountain page </a>;
? >
There are two methods of passing a session ID:

Cookies
URL parameters

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

session_id

SESSION_ID () is used to set or obtain the current session_id. either session_id () can be used in php5, or the session_id and Session_name of the current session can be obtained by the SID attached to the URL.

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

SESSION_ID () returns an empty string if no value is specified, the current session_id () is returned, and the current session does not start.

Check if session exists?

In previous versions of PHP, Session_is_register () was often used to check for the existence of sessions, and if you used $_session[' XXX ']=xxx to register session variables, 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 session_id for the current session, but not to change 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 only numbers, it contains at least one letter. Otherwise, a new session ID will be generated at every moment.

Example of Session name change:

<?php
$previous _name = Session_name ("WebSiteID");
echo "The new session name is: $previous _name<br/>";
? >
How do I delete a session?

1. unset ($_session[' xxx ') deletes a single session,unset ($_session[' xxx ')) to unregister a registered session variable. The effect is the same as Session_unregister (). Session_unregister () is no longer used in PHP5, and can be put into the doghouse.

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

2, $_session=array () Delete multiple sessions

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

Return value: Boolean value.

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

Session_unset () The function no longer works if $_session is used. Since PHP5 is bound to use $_session, this function can be shelved.

Here is the official PHP case for deleting the session:

<?php
Initializes the session.
Session_Start ();
/*** Delete all Session variables ... Unset ($_session[xxx]) can also be deleted individually. ****/
$_session = Array ();
/*** deletes the Sessin ID. Because the session defaults to cookies, use Setcookie to delete the cookie.***/that contains the session ID
if (Isset ($_cookie[session_name ())) {
Setcookie (Session_name (), ', Time ()-42000, '/');
}
Finally completely destroy session.
Session_destroy ();
? >
From this we can draw the step of deleting the session:

①session_start ()

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

③session_destroy ()

Session security:

The session module does not guarantee that the information stored in the session can only be seen by the user who created the session. Depending on the data it holds, more needs to be done to proactively protect the integrity of the session.

Evaluating the data that is carried in a session and enforcing additional safeguards usually cost a lot to reduce the user's convenience. For example, if you want to protect your users from simple social policies (note: The session ID displayed in the URL will be seen on the computer screen or by another Web site via HTTP Referer), you should enable session.use_only_cookies. In this case, the client must enable the cookie unconditionally, otherwise the session will not work.

There are several ways to leak an existing session ID to a third party. The leaked session ID enables third parties to access all resources associated with the specified ID. First, the URL carries the session ID. If you connect to a foreign site, a URL that contains a session ID may be present in the Referer log of the external site. Second, a more active attacker might listen for packets from the network segment. If unencrypted, the session ID flows through the network in clear text. The workaround for 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 every time a session is opened, a file is created, regardless of whether or not data is written to the file. Note This behavior has a side effect due to the limitations of working with the file system, which can cause user-tailored session processors, such as databases, to lose sessions that do 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, success returns the logical value TRUE

PHP5 no longer uses session_id, but instead turns it into a constant SID and saves it in a cookie. If the client disables cookie,php, the SID is automatically transmitted through the URL automatically, provided that the SESSION.USE_TRANS_SID = 1 is set in php.ini. It doesn't matter if the client even disables cookies at this point.

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

   Session Cross-page delivery problem:

There are three scenarios to consider for session spread delivery:

The ① client has disabled cookies.

② Browser is having problems, temporarily unable to access cookies

Session.use_trans_sid = 0 in ③php.ini or the--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 (the default is to store session by file), and the session ID is saved as a cookie on the client. (Note: Session defaults are based on cookies).

When a user's browser requests a server, a cookie containing the session ID (by default) is sent. The server comes to the user's file based on the session ID provided by the client, that is, the session variable value saved 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 Access URL. Later) to the server, and then the server reads the directory of the session .... In other words, the session ID is the identity card that gets the session variable stored on the service. When the Code session_start (), the runtime, on the server generated a session file, followed by a unique corresponding session ID, the definition of the session variable in a certain form stored in the session file just produced. With the session ID, you can take out the defined variables. After the page spread, in order to use the session, you must also execute session_start (), and will produce a session file, corresponding to produce the corresponding session ID, with this session The ID is not a variable in the first session file mentioned earlier, because the session ID is not the key to open it. If the code session_id ($session ID) is preceded by the session_start (), the new session file is not generated and the session file corresponding to this ID is read directly.

The session in PHP by default uses the client's cookie to save the sessions ID, so when the client's cookie has a problem, it will be affected. It is important to note that the session does not have to rely on cookies, which is a clever place to compare cookies to. When a client's cookie is disabled or a problem occurs, PHP automatically attaches the session ID to the URL, so that the session variable can be used across the page with the session ID. But this attachment is also a certain condition, one of: "php.ini in Session.use_trans_sid = 1 or compile-time open--enable-trans-sid option"; second: the server running PHP must be a unix/linux system, Windows does not have this feature.

Having understood the above, we can come up with three ways to solve the problem of Session cross-page delivery:

1, set the SESSION.USE_TRANS_SID = 1 in php.ini or compile-time open the--ENABLE-TRANS-SID option, let PHP automatically spread the session ID across the page.

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

3, in the form of files, databases and other forms of saving session_id, in the spread of the process of manual call.

The following examples illustrate:

In the 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 session variable var1 value of:". $_session[' var1 '];
? >
Run the above code, in case the client cookie is normal, you should be able to get the result "People's Republic of China".

Now you manually close the client's cookie, and then run, may not be the result of it. If you do not get the result, then "set the 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

<?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 as $url= ' <a Href= ' page2.php? '. Sid. ' "> next page </a>;
echo $url;
? >
s2.php

<?php
session_id ($_get[' s ']);
Session_Start ();
echo "passes the session variable var1 value of:". $_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 login:

<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 "User name or password is empty, please <a Href=\" login.html\ "and log back in </a>";
Die ();
}
if (!) ( $name = = "Laogong" && $pass = = "123")) {
echo "User name or password is incorrect, please <a Href=\" login.html\ "and log back in </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 actions
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 "Already logged in!";
}
else {
Successful login for related actions
echo "Not logged in, Access denied";
echo "Please <a Href=\" "Login.html\" > login </a> browse after ";
Die ();
}
? >



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.