Use the MySQL memory table to replace the PHP session class

Source: Internet
Author: User
Tags key string php session sql error

<? Php <br/>/** <br/> @ usage: use some other storage method (MySQL or memcache) instead of PHP sessoin <br/> @ Author: lein <br/> @ version: 1.2 <br/> */<br/> session_start (); <br/> If (! Isset ($ _ session ['test']) {<br/> $ _ session ['test'] = "123_lein _". date ("Y-m-d h: I: s "); <br/>}</P> <p> class session {</P> <p> // session data <br/> private $ data; <br/> // engine, MySQL or memcache <br/> private $ engine; <br/> // PHP session expire time <br/> private $ sessionexpiredtime; <br/> // current user's session cookie value <br/> private $ sessionid; <br/> // session coolie name <br/> private $ sessioncookiename; <B R/> Public Function session ($ enginebase = NULL, $ enginename = 'mysql', $ storage_name = 'php _ session ') {<br/> try {<br/> $ this-> sessionexpiredtime = intval (ini_get ("session. cache_expire ") * 10; // The default value is 180 minutes, which is too long and changed to 30 minutes <br/>} catch (exception $ exception) {<br/> $ this-> sessionexpiredtime = 1200; <br/>}< br/> try {<br/> $ this-> sessioncookiename = ini_get ("session. name "); <br/>}catch (exception $ exception) {<br/> $ this-> S Essioncookiename = 'phpsessid '; <br/>}</P> <p> If (! Isset ($ _ cookie [$ this-> sessioncookiename]) {<br/> @ session_start (); <br/> $ this-> sessionid = session_id (); <br/>} else {<br/> $ this-> sessionid = $ _ cookie [$ this-> sessioncookiename]; <br/>}< br/> $ classname = $ enginename. "sessionengine"; <br/> $ this-> engine = new $ classname (<br/> array (<br/> 'Storage _ name' => $ storage_name, // MySQL table name or memcahce key which stores data; <br/> 'expire _ time' => $ this-> session Expiredtime, <br/> 'data _ too_long_instead_value '=>' {__ data is * $ * to long __} '<br/> ), <br/> $ this-> sessionid, <br/> & $ enginebase <br/>); <br/> $ this-> Init (); <br/> $ this-> loadfromsession (); <br/> $ this-> engine-> refresh (); <br/> $ this-> engine-> cleanup (); <br/>}< br/> private function Init () <br/>{< br/> $ this-> DATA = $ this-> engine-> get (); <br/> If (empty ($ this-> data) {<br/> @ session_start (); <br/> If (! Empty ($ _ Session) {<br/> $ this-> data =$ _ Session; <br/> $ this-> engine-> Create (false, $ this-> data); <br/>}< br/> else <br/>{< br/> $ this-> engine-> Create (false, ""); <br/>}< br/> Public Function loadfromsession ($ flagstartsession = false) {<br/> $ flag = false; <br/> if ($ flagstartsession) {<br/> @ session_start (); <br/>}< br/> if ($ _ Session & is_array ($ _ Session )) {<br/> foreach ($ _ Session as $ k => $ v) {<br /> If (! Isset ($ this-> data [$ K]) {<br/> $ this-> data [$ K] = $ V; <br/> $ flag = true; <br/>}< br/> if ($ flag) {<br/> $ this-> engine-> set (false, $ this-> data); <br/>}< br/> private function _ Get ($ nm) <br/>{< br/> If (isset ($ this-> data [$ nm]) {<br/> $ r = $ this-> data [$ nm]; <br/> return $ R; <br/>}< br/> else <br/>{< br/> return NULL; <br/>}< br/> private function _ set ($ nm, $ Val) <br/>{< br/> $ This-> data [$ nm] = $ val; <br/> $ this-> engine-> set (false, $ this-> data ); <br/>}</P> <p> private function _ isset ($ nm) <br/>{< br/> return isset ($ this-> data [$ nm]); <br/>}</P> <p> private function _ unset ($ nm) <br/>{< br/> unset ($ this-> data [$ nm]); <br/> $ this-> engine-> set (false, $ this-> data); <br/>}</P> <p> function _ destruct () {<br/> $ this-> DATA = NULL; <br/> $ this-> engine-> close (); <br/> $ this-> Engine = NULL; <br/>}</P> <p> interface sessionengine <br/>{< br/>/* <br/> * Set varibles <br/> * @ Param $ arr array, array (varible name => Varible value ,...) <br/> */<br/> Public Function setvariable ($ ARR ); <br/>/* <br/> * Get session value <br/> * @ Param $ key string <br/> */<br/> Public Function get ($ key = ""); <br/>/* <br/> * set session value <br/> * @ Param $ key string <br/> * @ Param $ value string <B R/> */<br/> public function set ($ key = "", $ value = ""); <br/>/* <br/> * set session value <br/> * @ Param $ key string <br/> * @ Param $ value string <br/> */ <br/> public function create ($ key = "", $ value = ""); <br/>/* <br/> * update the session's invalid time <br/> * @ Param $ key string <br/> */<br/> Public Function refresh ($ key = ""); <br/>/* <br/> * close MySQL or memcache connection <br/> */<br/> Public fun Ction close (); <br/>/* <br/> * Delete expired sessions <br/> */<br/> Public Function cleanup (); <br/>}</P> <p> final class mysqlsessionengine implements sessionengine {<br/> private $ id = ""; <br/> private $ storage_name = 'php _ session'; <br/> private $ storage_name_slow = 'php _ session_slow '; <br/> private $ data_too_long_instead_value = '{__ data is ~ To long __} '; // if data is longer than $ max_session_data_length and you are using MySQL 4 or below, insert this value into memery table instead. <br/> private $ expire_time = 1200; <br/> private $ max_session_data_length = 2048; <br/> private $ conn; <br/> private $ mysql_version; <br/> Public Function mysqlsessionengine ($ arr = array (), $ key = "", & $ _ conn) {<br/> $ this-> setvariable ($ ARR); <br/> $ this-> id = $ key; <br/> I F (empty ($ this-> ID) | strlen ($ this-> ID )! = 32) {<br/> throw new exception (_ file __. "-> ". _ line __. ": Session's cookie name can't be empty and it must have just 32 charactors! "); <Br/>}< br/> $ this-> conn = $ _ conn; <br/> If (! $ This-> conn |! Is_resource ($ this-> conn) {<br/> throw new exception (_ file __. "-> ". _ line __. ": Need a MySQL connection! "); <Br/>}< br/> $ this-> mysql_version = $ this-> getone (" select floor (version ())"); <br/> if ($ this-> mysql_version <5) {<br/> $ this-> max_session_data_length = 255; <br/>}< br/> Public Function setvariable ($ ARR) {<br/> If (! Empty ($ ARR) & is_array ($ ARR) {<br/> foreach ($ arr as $ k => $ V) {<br/> $ this-> $ k = $ V; <br/> if ($ k = 'Storage _ name ') {<br/> $ this-> storage_name_slow = $ v. '_ slow'; <br/>}< br/> Public Function get ($ key = "") {<br/> if ($ key = "") $ key = $ this-> ID; <br/> $ return = $ this-> getone ('select value from '. $ this-> storage_name. 'Where id = "'. $ key. '"'); <br/> if ($ return = $ this-> data_too_long_instead_value) <BR/>{< br/> $ return = $ this-> getone ('select value from '. $ this-> storage_name_slow. 'Where id = "'. $ key. '"'); <br/>}< br/> If (! $ Return) <br/>{< br/> $ mysqlerror = mysql_error ($ this-> conn); <br/> If (strpos ($ mysqlerror, "doesn' t exist ")! = False) <br/>{< br/> $ this-> inittable (); <br/>}< br/> $ return = array (); <br/>}< br/> else <br/>{< br/> $ return = unserialize ($ return ); <br/>}< br/> return $ return; <br/>}< br/> public function close () {<br/> @ mysql_close ($ this-> conn); <br/>}< br/> Public Function cleanup () {<br/> if ($ this-> mysql_version> 4) {<br/> $ SQL = 'delete from '. $ this-> storage_name. 'Where date_add ('time', interval '. $ this-> expire_tim E. 'Second) <current_timestamp () '; <br/>}else {<br/> $ SQL = 'delete from '. $ this-> storage_name_slow. 'where'time' + '. $ this-> expire_time. '<unix_timestamp ()'; <br/> if ($ _ session ['username'] = "leinchu") {<br/> echo $ SQL; <br/>}< br/> $ this-> execute ($ SQL); <br/> $ SQL = 'delete from '. $ this-> storage_name. 'where'time' + '. $ this-> expire_time. '<unix_timestamp ()'; <br/> if ($ _ session ['username'] = "leinchu") {<br/> Echo $ SQL; <br/>}< br/> $ this-> execute ($ SQL ); <br/>}< br/> Public Function refresh ($ key = "") {<br/> if ($ this-> mysql_version> 4) {<br/> $ SQL = 'update '. $ this-> storage_name. 'set'time' = current_timestamp () Where id = "'. $ key. '"'; <br/>}else {<br/> $ SQL = 'update '. $ this-> storage_name. 'set'time' = unix_timestamp () Where id = "'. $ key. '"'; <br/>}< br/> $ return = $ this-> execute ($ SQL); <br/> If (! $ Return) {<br/> $ this-> inittable (); <br/> $ return = $ this-> execute ($ SQL, true ); <br/>}< br/> return $ return; <br/>}< br/> public function create ($ key = "", $ value = "") {<br/> if ($ key = "") $ key = $ this-> ID; <br/> if ($ value! = "") $ Value = mysql_real_escape_string (serialize ($ value), $ this-> conn); <br/> If (strlen ($ value)> $ this-> max_session_data_length) <br/>{< br/> if ($ this-> mysql_version> 4) {<br/> throw new exception (_ file __. "-> ". _ line __. ": session data is long than Max allow length (". $ this-> max_session_data_length. ")! "); <Br/>}< br/> if ($ this-> mysql_version> 4) {<br/> $ SQL = 'replace '. $ this-> storage_name. 'set value = /''. $ value. '/', id = "'. $ key. '", 'time' = current_timestamp ()'; <br/>} else {<br/> $ SQL = 'replace '. $ this-> storage_name. 'set value = /''. $ value. '/', id = "'. $ key. '", 'time' = unix_timestamp ()'; <br/>}< br/> $ return = $ this-> execute ($ SQL ); <br/> If (! $ Return) {<br/> $ this-> inittable (); <br/> $ return = $ this-> execute ($ SQL, true ); <br/>}< br/> return $ return; <br/>}< br/> public function set ($ key = "", $ value = "") {<br/> if ($ key = "") $ key = $ this-> ID; <br/> if ($ value! = "") $ Value = mysql_real_escape_string (serialize ($ value), $ this-> conn); <br/> $ SQL = 'update '. $ this-> storage_name. 'set value = /''. $ value. '/'where id = "'. $ key. '"'; <br/> If (strlen ($ value)> $ this-> max_session_data_length) <br/>{< br/> if ($ this-> mysql_version> 4) {<br/> throw new exception (_ file __. "-> ". _ line __. ": session data is long than Max allow length (". $ this-> max_session_data_length. ")! "); <Br/>}< br/> $ SQL = 'replace '. $ this-> storage_name_slow. 'set value = /''. $ value. '/', id = "'. $ key. '", 'time' = unix_timestamp ()'; <br/> $ this-> execute ($ SQL, true); <br/> $ SQL = 'update '. $ this-> storage_name. 'set value = /''. $ this-> data_too_long_instead_value. '/'where id = "'. $ key. '"'; <br/>}< br/> $ return = $ this-> execute ($ SQL); <br/> If (! $ Return) {<br/> $ this-> inittable (); <br/> $ return = $ this-> execute ($ SQL, true ); <br/>}< br/> return $ return; <br/>}< br/> private function inittable () {<br/> if ($ this-> mysql_version> 4) {<br/> $ SQL = "<br/> Create Table if not exists '". $ this-> storage_name. "'(<br/> 'id' char (32) not null default 'err', <br/> 'value' varbinary (". $ this-> max_session_data_length. ") null, <br/> 'time' timestamp not null defau Lt current_timestamp on update current_timestamp, <br/> Primary Key ('id'), <br/> key 'time' ('time') <br/>) engine = memory; <br/> "; <br/>}else {<br/> $ sqlslow =" <br/> Create Table if not exists '". $ this-> storage_name. "_ Slow '(<br/> 'id' char (32) not null default 'err', <br/> 'value' text null, <br/> 'time' int (10) Not null default '0', <br/> Primary Key ('id '), <br/> key 'time' ('time') <br/>) en Gine = MyISAM; <br/> "; <br/> $ this-> execute ($ sqlslow, true ); </P> <p> $ SQL = "<br/> Create Table if not exists '". $ this-> storage_name. "'(<br/> 'id' char (32) not null default 'err', <br/> 'value' varchar (255) null, <br/> 'time' int (10) Not null default '0', <br/> Primary Key ('id '), <br/> key 'time' ('time') <br/>) engine = memory; <br/> "; <br/>}< br/> return $ this-> execute ($ SQL, true); <br/>}< br/> private Function execute ($ SQL, $ die = false) <br/>{< br/> if ($ die) <br/>{< br/> mysql_query ($ SQL, $ this-> conn) or die ("exe SQL error: <br> ". mysql_error (). "<br> ". $ SQL. "<HR>"); <br/>}< br/> else <br/>{< br/> mysql_query ($ SQL, $ this-> conn ); <br/> If (mysql_error () {<br/> return false; <br/>}else {<br/> return true; <br/>}< br/> private function getone ($ SQL, $ die = false) {<br/> $ rs = $ this-> query ($ SQL, $ die); <br /> If ($ RS & ($ one = mysql_fetch_row ($ RS) {<br/> return $ one [0]; <br/>}else {<br/> return false; <br/>}< br/> private function query ($ SQL, $ die = false) {<br/> if ($ die) <br/> $ rs = mysql_query ($ SQL, $ this-> conn) or die ("query SQL error: <br> ". mysql_error (). "<br> ". $ SQL. "<HR>"); <br/> else <br/> $ rs = mysql_query ($ SQL, $ this-> conn); <br/> return $ RS; <br/>}< br/> $ lnk = mysql_connect ('localhost ',' Root ', '000000') <br/> or die ('not ccted :'. mysql_error (); </P> <p> // make Foo the current dB <br/> mysql_select_db ('test', $ lnk) or die ('can/'t use FOO :'. mysql_error (); <br/> $ S = new session ($ lnk); <br/> If (! $ S-> last) {<br/> $ S-> last = Time (); <br/>}< br/> echo "first visit ". $ S-> last. "<br>"; <br/> If (! $ S-> lastv) {<br/> $ S-> lastv = 0; <br/>}< br/> $ S-> lastv ++; <br/> echo "lastv = ". $ S-> lastv. "<br>"; <br/> echo "test = ". $ S-> test. "<br>"; <br/> If (isset ($ _ Get ['max ']) {<br/> $ S-> boom = str_repeat ("OK", 255 ); <br/>}< br/> If (isset ($ _ Get ['boom ']) {<br/> $ S-> boom =$ _ Get ['boom ']; <br/>}< br/> echo "boom = ". $ S-> boom. "<br>"; <br/>?> <Br/>

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.