Session usage in PHP

Source: Internet
Author: User
Tags define session echo date
What is session used in PHP?

The Chinese translation of a Session is called "Session". its original meaning refers to a series of actions/messages starting and ending, for example, a series of processes from picking up a phone call and dialing to hanging up a phone call can be called a session. At present, the society's understanding of sessions is very confusing: sometimes we can see this: "During a browser session ,... ", the session here refers to the period from opening to closing a browser window; you can also see the sentence" user (client) is in a session, it may refer to a series of actions of a user (generally a series of actions related to a specific purpose, such as the online shopping process from login to purchasing goods to checkout and logout; however, sometimes it may only mean a connection. The difference can only be inferred by context.

However, when a session is associated with a network protocol, it often implies two meanings: "connection-oriented" and "/" persistence, "Connection orientation" refers to the establishment of a communication channel before the communication parties establish a communication channel, such as a call, until the other party receives the telephone communication. "Keep status" means that the communication party can associate a series of messages so that messages can be mutually dependent, for example, a waiter can recognize an old customer who has visited the store again and remembers that the customer still owes a dollar to the store. Such examples include "one TCP session" or "one POP3 session ".

Since such chaos cannot be changed, it is difficult to have a unified standard for the next definition of the session. When reading session-related information, we can only infer and understand it by context. However, we can understand this as follows: for example, when we make a call, we call the call from the moment we call the call to the end of the call, because the call is always in the connected state, so we call the session status. It is a public variable that has existed throughout the interaction between visitors and the website. when the client does not support cookies, SESSION variables are used to ensure data correctness and security. Visitors to the website will be assigned a unique identifier, the so-called session ID. It is either a cookie stored on the client or transmitted through a URL.

The invention of the SESSION fills in the limitations of the HTTP protocol: the HTTP protocol is regarded as a stateless protocol and cannot be known about the user's browsing status. after the server completes the response, the server loses contact with the browser. This is consistent with the original purpose of the HTTP protocol. the client only needs to simply request the server to download some files, and neither the client nor the server needs to record the previous behaviors of each other, each request is independent, like the relationship between a customer and a vending machine or a common (non-member) hypermarket.

Therefore, SESSION (cookie is another solution) is used to record user information for confirmation when the user initiates a request to the web server. The invention of session allows a user to save his information when switching between multiple pages. Website programmers have such experiences that the variables on each page cannot be used on the next page (although form and url can also be implemented, this is a very bad way ), the variables registered in the SESSION can be used as global variables.

So what is the usefulness of SESSION? Shopping cart is used for online shopping. you can add the items you bought to the shopping cart at any time and check out the items at the cashier. During the whole process, the shopping cart has always played the role of temporarily storing the selected items and used it to track users' activities on the website. this is the role of SESSION, which can be used for user identity authentication, program Status record, parameter transfer between pages, etc.

The COOKIE technology is used in the implementation of the SESSION. The SESSION will save a COOKIE containing session_id (SESSION number) on the client, and save other session variables on the server, such as session_name. When a user requests a server, the session_id is also sent to the server. the session_id is used to extract the variables stored on the server to identify who the user is. At the same time, it is 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 "? The "custom level" item sets "allow COOKIE for each conversation" to disabled), session_id cannot be passed, and the SESSION becomes invalid. However, php5 can automatically check the cookie status on linux/unix platforms. if the client is disabled, the system automatically attaches session_id to the url for transmission. Windows host does not have this function.

Common Session functions and usage

Session_start (): start a session or return an existing session.

Note: This function has no parameters and returns true. If you use cookie-based sessions, the browser cannot output any output before Session_start (). Otherwise, 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 session. auto_start = 1 in php. ini, so you do not need to call session_start () every time before using the session (). However, enabling this option also has some restrictions. if the session is enabled. auto_start, the object cannot be put into the session, because the class definition must be loaded before the session is started to recreate the object in the session.

All registered variables are serialized after the request ends. Registered but undefined variables are marked as undefined. In subsequent access, these variables are not defined by the session module unless you define them later.

Warning some types of data cannot be serialized and therefore cannot be stored in sessions. Including resource variables or objects with circular references (that is, an object passes a reference pointing to itself to another object ).

Register SESSION variables:

PHP5 registers the SESSION global variable with $ _ SESSION ['XXX'] = xxx. Similar to GET, POST, and COOKIE usage.

Note: session_register (), session_unregister, and session_is_registered are no longer used in php5 unless register_globle is set to on in php. ini. However, it is strongly recommended to disable register_globle for security reasons. HTTP_SESSION_VARS is not recommended. we recommend that you use $ _ SESSION instead. For example:

Page1.php

View plaincopy to clipboardprint?

Session_start (); // This function must be called before SESSION is used.

$ _ SESSION ['name'] = "NowaMagic"; // register a SESSION variable

$ _ SESSION ['passwd'] = "hellomagic ";

$ _ SESSION ['Time'] = time ();

Echo'
Pass SESSION through COOKIE '; // if the client supports cookie, the session can be passed to the next page through this link.

Echo'
Use this method to pass SESSION 'Through URL; // when the client 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'
Back to the mountain page ';

?>

There are two ways to pass a Session ID:

One is cookie and the other is URL parameter.

The session module supports these two methods. Cookies are more optimized, but they are not always available and provide alternative methods. The second method directly embeds the session ID in the middle of the URL. PHP can transparently convert the connection. Unless PHP 4.2 or later is used, it needs to be activated when PHP is compiled manually. In Unix, use -- enable-trans-sid to configure options. If this configuration option and the runtime option session. use_trans_sid are activated (modify php. ini), the URI will be automatically changed to include session ID.

Session_id

Session_id () is used to set or obtain the current session_id. In php5, you can use session_id () or get the session_id and session_name of the current session by the SID appended to the url.

If session_id () has a specific value, it will replace the current session_id value. Before using this function, you must start the session: session_start ();

When session cookies are used, if a session_id () value is specified, each time session_start () is started, a cookie value will be sent to the client. Whether or not the current session_id is equal to the specified value.

If no value is specified for session_id (), the current session_id () is returned. if the current session is not started, an empty string is returned.

Check whether the session exists

In previous php versions, session_is_register () is used to check whether a session exists. if you use $ _ SESSION ['XXX'] = XXX to register a session variable, session_is_register () function no longer works. You can use isset ($ _ SESSION ['XXX']) instead.

Change session_id

Session_regenerate_id () returns true if the change is successful, and false if the change fails. This function can be used to change the session_id of the current session, but does not change other information of 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. To change the name of the current session, you must call this function before session_start. Note: session_name cannot be composed of only numbers. it must contain at least one letter. Otherwise, a new session id is generated every moment. Session renaming example:

View plaincopy to clipboardprint?

$ Previus_name = session_name ("WebsiteID ");

Echo "New session name: $ previus_name ";

?>

How to delete a session

Unset ($ _ SESSION ['XXX']) deletes a single session. unset ($ _ SESSION ['XXX']) is used to unregister a registered session variable. It works the same as session_unregister. Session_unregister () is no longer used in PHP5 and can be used in the cold Palace. Unset ($ _ SESSION) is not available. it destroys the global variable $ _ SESSION and there is no feasible way to restore it. You can no longer register the $ _ SESSION variable.

$ _ SESSION = array () delete multiple sessions

Session_destroy () ends the current session and clears all resources in the session. This function does not unset (release) the global variables related to the current session, nor delete the client session cookie. The default session of PHP is cookie-based. to delete a cookie, you must use the setcookie () function. Return value: Boolean value. Function description: This function ends the current session. this function has no parameters and returns true.

Session_unset () if $ _ SESSION is used, this function no longer works. Since PHP 5 must use $ _ SESSION, this function can be used in the cold room.

The following is an official PHP case concerning session deletion:

View plaincopy to clipboardprint?

// Initialize the session.

Session_start ();

/*** Delete all session variables .. You can also delete unset ($ _ SESSION [xxx]) one by one. ****/

$ _ SESSION = array ();

/*** Delete sessin id. because session is based on cookie by default, setcookie is used to delete the cookie containing session id .***/

If (isset ($ _ COOKIE [session_name ()])

{

Setcookie (session_name (), '', time ()-42000 ,'/');

}

// Finally, the session is completely destroyed.

Session_destroy ();

?>

The procedure for deleting a Session is as follows:

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 viewed by the user who created the session. Based on the data it stores, more measures need to be taken to actively protect the session integrity.

Evaluating the data carried in a session and implementing additional protection measures usually costs you to reduce your convenience. For example, if you want to protect users from simple social policies (note: the session ID displayed in the URL will be seen by others on the computer screen, or by another website through HTTP Referer), the session should be enabled. use_only_cookies. In this case, the client must enable cookie unconditionally, otherwise the session will not work.

There are several ways to disclose the existing session ID to a third party. The leaked session ID allows 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 containing a session ID may be stored in the Referer log of the external site. Second, more active attackers may listen on packets in the network segment. If not encrypted, the session ID passes through the network in plain text. The solution is to implement SSL on the server and force the user to use it.

By default, all data related to a specific session is stored in a file in the directory specified by session. save_path of The INI option. A file is created for each session (whether or not there is data related to the session ). This is because every time a session is opened, a file is created, whether or not data is written to the file. Note that due to restrictions on working with the file system, this behavior has a side effect, which may cause the loss of unstored data sessions in user-defined session processors (such as databases.

The functions described above will be used in the following sections, but there are also some functions related to the session:

Session_encode function: sesssion information encoding function prototype: string session_encode (void); return value: string function description: the returned string contains the name and value of each variable in the global variable, in the form: a | s: 12: "it is a test"; c | s: 4: "lala"; a is the variable name s: 12 represents the value of variable a. "The length of it is a test is 12. use semicolons (;) to separate variables.
Session_decode function: sesssion information decoding function prototype: boolean session_decode (string data) return value: boolean value function description: This function can decode session information. if successful, true is returned.

PHP5 no longer uses session_id, but changes it into a constant SID and stores it in the cookie. If the cookie is disabled on the client, php automatically transmits the SID through the url transmission, provided that session. use_trans_sid = 1 in php. ini is set. In this case, it does not matter even if the client disables the cookie. Use strip_tags () to output SID to avoid XSS-related attacks.

Cross-page Session transfer:

Session cross-page transmission requires three considerations:

The client disables cookies.

The browser has a problem and cannot access the cookie temporarily.

Session. use_trans_sid = 0 in php. ini or the -- enable-trans-sid option is not enabled during compilation.

Why? The reasons are as follows:

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

When your browser sends a request to the server, it also sends a cookie containing the session id (by default ). The server obtains the user's file based on the session id provided by the client, that is, the session variable value stored on the server. In fact, the session id can use the Cookie of the client or the Query_String of the Http1.1 protocol (that is, the "?" of the Accessed URL To the server, and then the server reads the Session directory. That is to say, session id is used to obtain the id card of the session variable stored in the service. When the code session_start (); is run, a session file is generated on the server, and a session id corresponding to it is also generated, define session variables to be stored in the generated session file in a certain form. The session id can be used to retrieve the defined variables. After a cross-page session, you must execute session_start (); a session file is generated, and the corresponding session id is generated, this session id cannot be used to retrieve the variables in the first session file mentioned above, because this session id is not the "key" to open it ". If the code session_id ($ session id) is added before session_start (); no new session file is generated and the session file corresponding to this id is directly read.

By default, the session in PHP uses the Cookie of the client to save the session id. Therefore, when the cookie of the client fails, the session will be affected. It must be noted that the session does not necessarily depend on the cookie, which is also a bit better than the cookie. When the Cookie on the client is disabled or a problem occurs, PHP automatically attaches the session id to the URL, so that the session variable can be used across pages through the session id. But this attachment also has certain conditions: "php. session in ini. use_trans_sid = 1 or the -- enable-trans-sid option is enabled during compilation. Second, the server running PHP must be a unix/linux System. windows does not have this function.

After understanding the above principles, we can come up with three ways to solve the cross-page session transfer problem:

Set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option when compiling, so that PHP can automatically pass the session id across pages.

Manually pass session IDs through URL values and hidden forms.

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

The following is an example:

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 "the value of the passed session variable var1 is:". $ _ SESSION ['var1'];

?>

Run the above code. when the client cookie is normal, you can obtain the result "People's Republic of China ".

Now you can manually close the client cookie and run it again. The result may not be returned. If no result is returned, "set session. use_trans_sid = 1 in php. ini or enable the -- enable-trans-sid option during compilation", and the "People's Republic of China" is returned ".

The second approach:

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 as $ url = 'next page ';

$ Url = "next page ";

Echo $ url;

?>

S2.php

View plaincopy to clipboardprint?

Session_id ($ _ GET ['s ']);

Session_start ();

Echo "the value of the passed session variable var1 is:". $ _ SESSION ['var1'];

?>

Third approach:

Login.html

View plaincopy to clipboardprint?

Login

Please log on:

Mylogin1.php

$ Name = $ _ POST ['name'];

$ Pass = $ _ POST ['pass'];

If (! $ Name |! $ Pass ){

Echo "the user name or password is blank. please log on again ";

Die ();

}

If (! ($ Name = "laogong" & $ pass = "123 ")){

Echo "the user name or password is incorrect. please log on again ";

Die ();

}

// Register a user

Ob_start ();

Session_start ();

$ _ SESSION ['user'] = $ name;

$ Psid = session_id ();

$ Fp = fopen ("e: \ tmp \ phpsid.txt", "w + ");

Fwrite ($ fp, $ psid );

Fclose ($ fp );

// Complete the authentication.

Echo "logged on
";

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

}

Else

{

// Log on successfully for related operations

Echo "not logged on, not authorized to access ";

Echo "log on and browse ";

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.