The CI Session is not a native session. it is exactly all of my previous cookiebasedsessions. In addition, CI can choose whether to save the session to the database based on the user-selected configuration. I like this function very much, there is & amp;
The CI Session is not a native session. it is all the cookie-based sessions in front of me. In addition, CI can choose whether to store the session into the database based on the user-selected configuration. I like this function very much, there is also the "flash data" function, which means that only the next request to the server is allowed to flash data and will be automatically cleared later. Common usage methods include:
$ This-> session-> set_userdata ('Some _ name', 'Some _ value'); // Set session data
$ This-> session-> userdata ('ITEM'); // Get session data
$ This-> session-> unset_userdata ('Some _ name'); // delete session data
$ This-> session-> sess_destroy (); // destroy session data
$ This-> session-> set_flashdata ('item', 'value'); // sets the flash data.
$ This-> session-> flashdata ('ITEM'); // Obtain the flash data
$ This-> session-> keep_flashdata ('ITEM'); // retain the flash data
/*** CI is a session based cookie ** @ link http://www.phpddt.com */Class CI_Session {var $ sess_encrypt_cookie = FALSE; // whether to encrypt the session var $ sess_use_database = FALSE; // whether to save the session to the database var $ sess_table_name = ''; // The table name var $ sess_expiration = 7200; // the expiration time of the session var $ sess_expire_on_close = FALSE; // whether the session will expire automatically when the browser window is closed. var $ sess_match_ip = FALSE; // whether to read the session data through the user's IP address var $ sess_match_useragent = TRUE; // whether to read session data according to the corresponding User Agent. Var $ sess_cookie_name = 'ci _ session'; // cookie name var $ cookie_prefix = ''; // cookie prefix var $ cookie_path = ''; // cookie path var $ cookie_domain = ''; // cookie scope var $ cookie_secure = FALSE; // whether var $ sess_time_to_update = 300 is valid under secure https protocol; // How often does a session cookie update var $ encryption_key = ''; // encrypt keyvar $ flashdata_key = 'Flash'; var $ time_reference = 'time'; var $ gc_probability = 5; // reclaim the session capability var $ userdata = array (); // use User session data storage variable var $ CI; // CI Super handle var $ now; // Current Time public function _ construct ($ params = array ()) {log_message ('debug', "Session Class Initialized"); // Obtain the CI super Class $ this-> CI = & get_instance (); // Obtain the configuration data in the config file foreach (array ('sess _ encrypt_cookie ', 'sess _ use_database', 'sess _ table_name ', 'sess _ expiration ', 'sess _ expire_on_close ', 'sess _ match_ip', 'sess _ match_useragent ', 'sess _ cookie_name', 'Cookie _ path', 'C Ookie_domain ', 'Cookie _ secure', 'sess _ time_to_update ', 'Time _ reference', 'Cookie _ prefix', 'encryption _ key') as $ key) {$ this-> $ key = (isset ($ params [$ key])? $ Params [$ key]: $ this-> CI-> config-> item ($ key);} // encryption_keyif ($ this-> encryption_key = '') must be set '') {show_error ('in order to use the Session class you are required to set an encryption key In your config file. ');} // load string helper function $ this-> CI-> load-> helper ('string'); // D if the cookie is encrypted, the encryption class if ($ this-> sess_encrypt_cookie = TRUE) {$ this-> CI-> load-> library ('encrypt');} is introduced ');} // if the session is included in the database, dbif ($ this -> Sess_use_database === true and $ this-> sess_table_name! = '') {$ This-> CI-> load-> database ();} // Obtain the current time $ this-> now = $ this-> _ get_time (); // if the validity period of the session is not set, the default value is two years if ($ this-> sess_expiration = 0) {$ this-> sess_expiration = (60*60*24*365*2);} // Obtain the cookie name $ this-> sess_cookie_name = $ this-> cookie_prefix. $ this-> sess_cookie_name; // if the session does not exist, create a new session if (! $ This-> sess_read () {$ this-> sess_create ();} else {$ this-> sess_update ();} // flash out the data marked as old $ this-> _ flashdata_sweep (); // The new data marked as old will flash $ this-> _ flashdata_mark () at the next request (); // Recycle/delete expired sessions $ this-> _ sess_gc (); log_message ('debug', "session routines successfully run ");} // ----------------------------------------------------------------------/*** read session data */function sess_read () {// Obtain session $ sessio N = $ this-> CI-> input-> cookie ($ this-> sess_cookie_name); // if ($ session = FALSE) {log_message ('debug', 'a session cookie was not found. '); return FALSE;} // If cookieif ($ this-> sess_encrypt_cookie = TRUE) is encrypted) {$ session = $ this-> CI-> encrypt-> decode ($ session);} else {// encryption was not used, so we need to check the md5 hash $ hash = substr ($ session, strlen ($ session)-32); // get last 32 chars $ s Ession = substr ($ session, 0, strlen ($ session)-32); // Does the md5 hash match? This is to prevent manipulation of session data in userspaceif ($ hash! = Md5 ($ session. $ this-> encryption_key) {log_message ('error', 'session cookie data did not match what was expected. this cocould be a possible hacking attempt. '); $ this-> sess_destroy (); return FALSE;} // deserialize the session array saved to the cookie $ session = $ this-> _ unserialize ($ session ); // Check the session data if (! Is_array ($ session) OR! Isset ($ session ['session _ id']) OR! Isset ($ session ['IP _ address']) OR! Isset ($ session ['User _ agent']) OR! Isset ($ session ['last _ active']) {$ this-> sess_destroy (); return FALSE ;} // is the session data expired? if ($ session ['last _ activity'] + $ this-> sess_expiration) <$ this-> now) {$ this-> sess_destroy (); return FALSE ;} // whether the session data is read based on the user ip address. if ($ this-> sess_match_ip = true and $ session ['IP _ address']! = $ This-> CI-> input-> ip_address () {$ this-> sess_destroy (); return FALSE ;} // whether to match session data based on ua if ($ this-> sess_match_useragent = true and trim ($ session ['User _ agent'])! = Trim (substr ($ this-> CI-> input-> user_agent (), 0,120) {$ this-> sess_destroy (); return FALSE ;} // if the session is stored in the database, this method should be more secure. of course, when the load is large, it is not recommended. if ($ this-> sess_use_database = TRUE) {$ this-> CI-> db-> where ('session _ id', $ session ['session _ id']); if ($ this-> sess_match_ip = TRUE) {$ this-> CI-> db-> where ('IP _ address ', $ session ['IP _ address']);} if ($ this-> sess_match_useragent = TRUE) {$ this-> CI-> db-> where ('User _ Gent ', $ session ['User _ agent']);} $ query = $ this-> CI-> db-> get ($ this-> sess_table_name ); // No result? Kill it! If ($ query-> num_rows () = 0) {$ this-> sess_destroy (); return FALSE;} // Is there custom data? If so, add it to the main session array $ row = $ query-> row (); if (isset ($ row-> user_data) AND $ row-> user_data! = '') {$ Custom_data = $ this-> _ unserialize ($ row-> user_data); if (is_array ($ custom_data )) {foreach ($ custom_data as $ key => $ val) {$ session [$ key] = $ val ;}}// Session is valid! $ This-> userdata = $ session; unset ($ session); return TRUE;} // combine/*** write the read session data to */function sess_write () {// whether to write dbif ($ this-> sess_use_database === FALSE) {$ this-> _ set_cookie (); return ;}// set the custom userdata, the session data we will set in a second $ custom_userdata = $ this-> userdata; $ cookie_userdata = array (); // Before continuing, We need to determine if there is any custom data to deal. // Let's determine this by removing the default indexes to see if there's anything left in the array // and set the session data while we're at itforeach (array (' session _ id ', 'IP _ address', 'User _ agent', 'Last _ activity') as $ val) {unset ($ custom_userdata [$ val]); $ cookie_userdata [$ val] = $ this-> userdata [$ val];} // Did we find any custom data? If not, we turn the empty array into a string // since there's no reason to serialize and store an empty array in the DBif (count ($ custom_userdata) = 0) {$ custom_userdata = '';} else {// Serialize the custom data array so we can store it $ custom_userdata = $ this-> _ serialize ($ custom_userdata );} // update the session record $ this-> CI-> db-> where ('session _ id', $ this-> userdata ['session _ id']); $ this-> CI-> db-> update ($ this-> Sess_table_name, array ('last _ activity' => $ this-> userdata ['last _ active'], 'User _ data' => $ custom_userdata )); // Write the cookie. notice that we manually pass the cookie data array to the // _ set_cookie () function. normally that function will store $ this-> userdata, but // in this case that array contains custom data, which we do not want in the cookie. $ this-> _ set_cookie ($ cookie_userdata );}//------ Else/*** create a new session */function sess_create () {// ensure that sessid is secure and unique $ sessid = ''; while (strlen ($ sessid) <32) {$ sessid. = mt_rand (0, mt_getrandmax ();} $ sessid. = $ this-> CI-> input-> ip_address (); $ this-> userdata = array ('session _ id' => md5 (uniqid ($ sessid, TRUE), 'Ip _ address' =>$ this-> CI-> input-> ip_address (), 'user _ agent' => substr ($ this-> CI-> input-> u Ser_agent (), 0,120), 'Last _ activity' => $ this-> now, 'User _ data' => ''); // Save the data to the DB if neededif ($ this-> sess_use_database === TRUE) {$ this-> CI-> db-> query ($ this-> CI-> db-> insert_string ($ this-> sess_table_name, $ this-> userdata ));} // Write the cookie $ this-> _ set_cookie ();} // Updated/*** UPDATE session */function sess_update () {// update I by default. F ($ this-> userdata ['last _ activity'] + $ this-> sess_time_to_update) >=$ this-> now) {return ;} // Save the old session id so we know which record to // update in the database if we need it $ old_sessid = $ this-> userdata ['session _ id']; $ new_sessid = ''; while (strlen ($ new_sessid) <32) {$ new_sessid. = mt_rand (0, mt_getrandmax ();} // To make the session ID even more secure we'll combine it with the user's IP $ n Ew_sessid. = $ this-> CI-> input-> ip_address (); // Turn it into a hash $ new_sessid = md5 (uniqid ($ new_sessid, TRUE )); // Update the session data in the session data array $ this-> userdata ['session _ id'] = $ new_sessid; $ this-> userdata ['last _ active'] = $ this-> now; // _ set_cookie () will handle this for us if we aren't using database sessions // by pushing all userdata to the cookie. $ cookie_data = NULL; // update the database Probability if ($ this-> sess_use_database === TRUE) {// set cookie explicitly to only have our session data $ cookie_data = array (); foreach (array ('session _ id', 'Ip _ address', 'User _ agent', 'Last _ active') as $ val) {$ cookie_data [$ val] = $ this-> userdata [$ val];} $ this-> CI-> db-> query ($ this-> CI-> db-> update_string ($ this-> sess_table_name, array ('last _ activity' => $ this-> now, 'session _ id' => $ new_sessid), array ('session _ id '=> $ Old_sessid);} // re-write session $ this-> _ set_cookie ($ cookie_data );} // ----------------------------------------------------------------------/*** destroy all current session data */function sess_destroy () {// Kill the session DB rowif ($ this-> sess_use_database === TRUE & isset ($ this-> userdata ['session _ id']) {$ this-> CI-> db-> where ('session _ id', $ this-> userdata ['session _ id']); $ this-> CI-> db-> delete ($ this-> sess_table_na Me);} // Kill the cookiesetcookie ($ this-> sess_cookie_name, addslashes (serialize (array (), ($ this-> now-31500000 ), $ this-> cookie_path, $ this-> cookie_domain, 0); // Kill session data $ this-> userdata = array ();} // ----------------------------------------------------------------------/*** get the value of the specified element of the session array */function userdata ($ item) {return (! Isset ($ this-> userdata [$ item])? FALSE: $ this-> userdata [$ item];} // users/*** get all session data */function all_userdata () {return $ this-> userdata ;} // --------------------------------------------------------------------/*** add and modify custom session data */function set_userdata ($ newdata = array (), $ newval = '') {if (is_string ($ newdata) {$ newdata = array ($ newdata => $ newval);} // array combination supported Method if (count ($ newdata)> 0) {foreach ($ newdata as $ key => $ val) {$ this-> userdata [$ key] = $ val ;}} $ this-> sess_write ();} // deletes/*** deletes the elements in the session array, */function unset_userdata ($ newdata = array ()) {if (is_string ($ newdata) {$ newdata = array ($ newdata => '');} if (count ($ newdata)> 0) {foreach ($ newdata as $ key => $ val) {unset ($ this-> userdata [$ key]) ;}$ This-> sess_write () ;}// ----------------------------------------------------------------------/*** Add or change flashdata, only available * until the next request ** @ accesspublic * @ parammixed * @ paramstring * @ returnvoid */function set_flashdata ($ newdata = array (), $ newval = '') {if (is_string ($ newdata) {$ newdata = array ($ newdata => $ newval);} if (count ($ newdata)> 0) {foreach ($ newdata $ Key => $ val) {$ flashdata_key = $ this-> flashdata_key. ': new :'. $ key; $ this-> set_userdata ($ flashdata_key, $ val) ;}}// assets/*** CI supports data flash, that is, Session data is only available for the Next server request, sometimes, if you want to make the next request still valid... * The keep_flashdata function is to keep the flash data valid for the next request. */function keep_flashdata ($ key) {// Mark the flash data as new $ old_flashdata_key = $ this-> flashdata_key. ': old :'. $ key; $ value = $ this-> userdata ($ old_flashdata_key); $ new_flashdata_key = $ this-> flashdata_key. ': new :'. $ key; $ this-> set_userdata ($ new_flashdata_key, $ value);} // outputs/*** get the flashdata */function flashdata ($ Key) {$ flashdata_key = $ this-> flashdata_key. ': old :'. $ key; return $ this-> userdata ($ flashdata_key);} // ------------------------------------------------------------------/*** mark the flash data as old, so that _ flashdata_sweep clears data */function _ flashdata_mark () {$ userdata = $ this-> all_userdata (); foreach ($ userdata as $ name => $ value) {$ parts = explode (': new:', $ name); if (is_array ($ parts) & count ($ parts) === 2) {$ new_na Me = $ this-> flashdata_key. ': old :'. $ parts [1]; $ this-> set_userdata ($ new_name, $ value); $ this-> unset_userdata ($ name );}}} // outputs/*** flash the flash data marked as old */function _ flashdata_sweep () {$ userdata = $ this-> all_userdata (); foreach ($ userdata as $ key => $ value) {if (strpos ($ key, ': old :')) {$ this-> unset_userdata ($ key) ;}}// obtain the current time function _ get_time (){ If (strtolower ($ this-> time_reference) = 'gmt') {$ now = time (); $ time = mktime (gmdate ("H", $ now ), gmdate ("I", $ now), gmdate ("s", $ now), gmdate ("m", $ now), gmdate ("d", $ now ), gmdate ("Y", $ now);} else {$ time = time ();} return $ time ;} // compile/*** write session cookie **/function _ set_cookie ($ cookie_data = NULL) {if (is_null ($ cookie_data) {$ cooki E_data = $ this-> userdata;} // serialized array $ cookie_data = $ this-> _ serialize ($ cookie_data ); // encrypt data if ($ this-> sess_encrypt_cookie = TRUE) {$ cookie_data = $ this-> CI-> encrypt-> encode ($ cookie_data );} else {// if encryption is not used, we provide an md5 hash to prevent userside tampering $ cookie_data = $ cookie_data.md5 ($ cookie_data. $ this-> encryption_key);} // If sess_expire_on_close is TRUE, the browser closes and the session becomes invalid. $ expire = ($ th Is-> sess_expire_on_close = TRUE )? 0: $ this-> sess_expiration + time (); // Set the cookiesetcookie ($ this-> sess_cookie_name, $ cookie_data, $ expire, $ this-> cookie_path, $ this-> cookie_domain, $ this-> cookie_secure);} // serialize/*** serialize array */function _ serialize ($ data) {if (is_array ($ data) {foreach ($ data as $ key => $ val) {if (is_string ($ val )) {$ data [$ key] = str_replace ('\', '{slash }}', $ Val) ;}} else {if (is_string ($ data) {$ data = str_replace ('\', '{slash }}', $ data) ;}} return serialize ($ data) ;}// ------------------------------------------------------------------/*** deserialization array */function _ unserialize ($ data) {$ data = @ unserialize (strip_slashes ($ data); if (is_array ($ data) {foreach ($ data as $ key => $ val) {if (is_string ($ val) {$ data [$ key] = str_replace ('{slash}', '\', $ val) ;}} retu Rn $ data;} return (is_string ($ data ))? Str_replace ('{slash}', '\', $ data): $ data ;} // revoke/*** reclaim/delete invalid session information in the database */function _ sess_gc () {if ($ this-> sess_use_database! = TRUE) {return;} srand (time (); if (rand () % 100) <$ this-> gc_probability) {$ expire = $ this-> now-$ this-> sess_expiration; $ this-> CI-> db-> where ("last_activity <{$ expire }"); $ this-> CI-> db-> delete ($ this-> sess_table_name); log_message ('debug', 'session garbage collection completed Med. ');}}}