This article describes in detail the Session object in PHP, from the concept to how to create, and then to the general structure. Hope to help you. let's take a look. Compared with cookies in PHP Development, session is stored on the server side, which is relatively secure and does not have storage length restrictions like cookies. The following is an introduction to the Session.
Session and Cookie in php
Compared with cookies in PHP Development, session is stored on the server, which is relatively secure and has a storage length limit unlike Cookie. This article briefly introduces the use of session.
The Session is stored on the server as a text file, so the client is not afraid to modify the Session content. In fact, in the Session file on the server side, PHP automatically modifies the session file permissions, only retaining the system read and write permissions, and cannot be modified through ftp, which is much safer.
For Cookie, if we want to verify whether the user logs in, we must save the user name and password (which may be the md5 encrypted string) in the Cookie and perform verification on each request page. If the user name and password are stored in the database, a database query is executed every time, causing extra burden on the database. Because we cannot perform only one verification. Why? Because the information in the client Cookie may be modified. If you store the $ admin variable to indicate whether the user has logged on, $ admin indicates logging on when it is set to true, and false indicates not logging on, after the first verification is passed, $ admin equals true is stored in the Cookie, so no verification is required next time. is this correct? Wrong. if someone spoofs a $ admin variable with the value true, isn't the administrator privilege immediately obtained? Very insecure.
The Session is different. The Session is stored on the server, and remote users cannot modify the content of the session file. Therefore, we can simply store a $ admin variable to determine whether to log on, after the first verification is passed, set $ admin to true, and then judge whether the value is true. if not, transfer it to the login interface, which can reduce a lot of database operations. In addition, it can reduce the security of passing passwords to verify cookies every time (session verification only needs to be passed once, if you do not use the SSL security protocol ). Even if the password is encrypted with md5, it is easily intercepted.
Of course, session has many advantages, such as easy control and user-defined storage (stored in the database ). I will not talk about it here.
Does session need to be set in php. ini? Generally, this is not required because not everyone has modified PHP. ini permission. The Default session storage path is the temporary system folder of the server. we can customize it to be stored in our own folder. I will introduce it later.
How to create a Session in Php
This topic describes how to create a session. Very simple, really.
Start the session and create a $ admin variable:
// Start session session_start (); // declare a variable named admin and assign a null value. $ _ Session ["admin"] = null;?>
If you use a Session or the PHP file needs to call the Session variable, you must start the Session before calling it and use the session_start () function. PHP automatically creates the session file.
After executing this program, we can find the session file in the temporary folder of the system. the file name is generally sess_4c83638b3b0dbf65583181c2f89168ec, followed by a 32-bit encoded random string. Open it in the editor and check its content:
admin|N;
General content structure:
Variable name | type: Length: value;
Separate each variable with a semicolon. Some can be omitted, such as length and type.
Let's take a look at the verification program. assume that the database stores the user name and the md5 encrypted password:
// After the form is submitted... $ posts =$ _ POST; // clear some blank symbols foreach ($ posts as $ key =>$ value) {$ posts [$ key] = trim ($ value );} $ password = md5 ($ posts ["password"]); $ username = $ posts ["username"]; $ query = "SELECT 'username' FROM 'user' WHERE 'password' = '$ password '"; // Get the query result $ userInfo = $ DB-> getRow ($ query); if (! Emptyempty ($ userInfo) {if ($ userInfo ["username"] ==$ username) {// after the verification is passed, start session session_start (); // register the logon admin variable and assign the value true $ _ SESSION ["admin"] = true;} else {die ("username and password error ");}} else {die ("incorrect user name and password ");}
We start the session on the page that requires user verification to determine whether to log on:
// Prevent security risks caused by global variables $ admin = false; // start the session. This step is required for session_start (); // determine whether to log on to if (isset ($ _ SESSION ["admin"]) & $ _ SESSION ["admin"] = true) {echo "you have successfully logged on";} else {// verification failed. set $ _ session ["admin"] to false $ _ SESSION ["admin"] = false; die ("You are not authorized to access") ;}?>
Is it easy? Consider $ _ session as an array stored on the server. every variable we register is an array key, which is no different from the array used.
What if I want to log out of the system? Destroy the session.
<? Php session_start (); // This method destroys a previously registered variable unset ($ _ SESSION ["admin"]); // This method destroys the entire session file session_destroy ();?>
Can a Session set a lifecycle like a Cookie? Does Session discard cookies? I would like to say that using session with cookies is the most convenient.
How does the Session determine the client user? It is determined by the Session ID. what is the Session ID is the name of the Session file, and the Session ID is randomly generated. Therefore, the uniqueness and randomness can be ensured to ensure the security of the Session. Generally, if the Session life cycle is not set, the Session ID is stored in the memory. when the browser is closed, the ID is automatically deregistered. after the page is requested again, a session ID is re-registered.
If the client does not disable the Cookie, the Cookie plays the role of storing the Session ID and Session lifetime when the session is started. Let's manually set the session lifetime:
Session_start (); // save a day $ lifeTime = 24*3600; setcookie (session_name (), session_id (), time () + $ lifeTime, "/");?>
In fact, the Session also provides a function session_set_cookie_params (); to set the Session lifetime. this function must be called before the session_start () function is called:
// Save for one day <? Php $ lifeTime = 24*3600; session_set_cookie_params ($ lifeTime); session_start (); $ _ session ["admin"] = true;?>
If the client uses IE 6.0, session_set_cookie_params (); the function sets the Cookie. Therefore, we need to manually call the setcookie function to create the cookie.
What if the client disables cookies? No way. all life cycles are browser processes. you only need to close the browser and request the page to register the Session again. So how to pass the Session ID? Through URL or by hiding the form to pass, PHP will automatically send session ID to the URL, URL-like: http://www.openphp. cn/index. php? PHPSESSID = bba5b2a240a77e5b44cfa01d49cf9669. the PHPSESSID parameter in the URL is the Session ID. we can use $ _ GET to obtain this value, so that the session ID can be transmitted between pages.
// Save for one day <? Php $ lifeTime = 24*3600; // Obtain the current session name. The default value is PHPSESSID $ sessionName = session_name (); // Obtain the session ID $ sessionID =$ _ GET [$ sessionName]; // use session_id () to set the session ID session_id ($ sessionID); session_set_cookie_params ($ lifeTime ); session_start (); $ _ session ["admin"] = true;?>
For a VM, if all users' sessions are saved in a temporary system folder, maintenance is difficult and security is reduced. you can manually set the Session file storage path, session_save_path () provides such a function. We can direct the session directory to a folder that cannot be accessed through the Web. of course, this folder must have the read/write attribute.
<? Php // set a storage directory $ savePath = ". /session_save_dir/"; // save for one day $ lifeTime = 24*3600; session_save_path ($ savePath); session_set_cookie_params ($ lifeTime); session_start (); $ _ session ["admin"] = true;?>
Like the session_set_cookie_params (); function, the session_save_path () function must also be called before the session_start () function is called. We can also store arrays and objects in sessions. There is no difference between an operation array and an operation variable. if you save an object, PHP will automatically serialize the object (also called serialization) and save it in the session. The following example illustrates this:
<? Php class person {var $ age; function output () {echo $ this-> age;} function setAge ($ age) {$ this-> age = $ age ;}}?> Setage. PHP <? Php session_start (); require_once "person. PHP "; $ person = new person (); $ person-> setAge (21); $ _ session ['person '] = $ person; echo "check here to output age";?> Output. PHP <? Php // Set the callback function to ensure that the object is rebuilt. Ini_set ('unserialize _ callback_func ', 'mycallback'); function mycallback ($ classname) {$ classname. ". PHP ";} session_start (); $ person = $ _ session [" person "]; // output 21 $ person-> output ();?>
When we execute setage. in the php file, the setage () method is called, the age is set to 21, and the status is serialized and saved in the session (PHP will automatically complete this conversion ), when it is switched to output. after php, to output this value, you must deserialize the saved object. because an undefined class needs to be instantiated during deserialization, we have defined the callback function in the future, automatically contains person. PHP class file. Therefore, the object is restructured and the current age value is 21. then, the output () method is called to output the value.
At this point, we have finished introducing how to use the Session in PHP. I hope it will be helpful for your learning.