A class that replaces the PHP session with a MySQL memory table

Source: Internet
Author: User
Tags key string php session sql error
  1. /**
  2. * Session MySQL Memory table
  3. @Usage: Use some other storage method (MySQL or memcache) instead of PHP Sessoin
  4. @author: Lein
  5. @Version: 1.2
  6. */
  7. Session_Start ();
  8. if (!isset ($_session[' test ')) {
  9. $_session[' test ']= "123_lein_". Date ("y-m-d h:i:s");
  10. }
  11. Class session{
  12. Session data
  13. Private $data;
  14. Engine,mysql or Memcache
  15. Private $engine;
  16. PHP Session expire Time
  17. Private $sessionexpiredTime;
  18. Current user ' s session cookie value
  19. Private $sessionID;
  20. Session Coolie Name
  21. Private $sessionCookieName;
  22. Public Function session ($engineBase =null, $engineName = ' mysql ', $storage _name= ' php_session ') {
  23. try{
  24. $this->sessionexpiredtime = intval (Ini_get ("Session.cache_expire") *10;//default is 180 minutes, too long, changed to 30 minutes
  25. }catch (Exception $Exception) {
  26. $this->sessionexpiredtime = 1200;
  27. }
  28. try{
  29. $this->sessioncookiename = Ini_get ("Session.name");
  30. }catch (Exception $Exception) {
  31. $this->sessioncookiename = ' PHPSESSID ';
  32. }
  33. if (!isset ($_cookie[$this->sessioncookiename])) {
  34. @session_start ();
  35. $this->sessionid=session_id ();
  36. }else{
  37. $this->sessionid=$_cookie[$this->sessioncookiename];
  38. }
  39. $className = $engineName. " Sessionengine ";
  40. $this->engine = new $className (
  41. Array
  42. ' Storage_name ' = $storage _name,//mysql table name or MEMCAHCE key which stores data;
  43. ' Expire_time ' = $this->sessionexpiredtime,
  44. ' Data_too_long_instead_value ' = ' {__data is *$* to long__} '
  45. ),
  46. $this->sessionid,
  47. & $engineBase
  48. );
  49. $this->init ();
  50. $this->loadfromsession ();
  51. $this->engine->refresh ();
  52. $this->engine->cleanup ();
  53. }
  54. Private Function init ()
  55. {
  56. $this->data = $this->engine->get ();
  57. if (Empty ($this->data)) {
  58. @session_start ();
  59. if (!empty ($_session)) {
  60. $this->data = $_session;
  61. $this->engine->create (False, $this->data);
  62. }
  63. Else
  64. {
  65. $this->engine->create (False, "");
  66. }
  67. }
  68. }
  69. Public Function loadfromsession ($flagStartSession = False) {
  70. $flag =false;
  71. if ($flagStartSession) {
  72. @session_start ();
  73. }
  74. if ($_session&&is_array ($_session)) {
  75. foreach ($_session as $k = = $v) {
  76. if (!isset ($this->data[$k])) {
  77. $this->data[$k] = $v;
  78. $flag =true;
  79. }
  80. }
  81. }
  82. if ($flag) {
  83. $this->engine->set (False, $this->data);
  84. }
  85. }
  86. Private Function __get ($NM)
  87. {
  88. if (Isset ($this->data[$nm])) {
  89. $r = $this->data[$nm];
  90. return $r;
  91. }
  92. Else
  93. {
  94. return NULL;
  95. }
  96. }
  97. Private Function __set ($NM, $val)
  98. {
  99. $this->data[$nm] = $val;
  100. $this->engine->set (False, $this->data);
  101. }
  102. Private Function __isset ($NM)
  103. {
  104. return Isset ($this->data[$nm]);
  105. }
  106. Private Function __unset ($NM)
  107. {
  108. unset ($this->data[$nm]);
  109. $this->engine->set (False, $this->data);
  110. }
  111. function __destruct () {
  112. $this->data = NULL;
  113. $this->engine->close ();
  114. $this->engine = NULL;
  115. }
  116. }
  117. Interface Sessionengine
  118. {
  119. /*
  120. * Set Varibles
  121. * @param $arr Array,array (varible name=>varible value,...)
  122. */
  123. Public Function setvariable ($arr);
  124. /*
  125. * Get Session value
  126. * @param $key string
  127. */
  128. Public function Get ($key = "");
  129. /*
  130. * Set Session value
  131. * @param $key string
  132. * @param $value string
  133. */
  134. Public function set ($key = "", $value = "");
  135. /*
  136. * Set Session value
  137. * @param $key string
  138. * @param $value string
  139. */
  140. Public Function Create ($key = "", $value = "");
  141. /*
  142. * Update the session ' s invalid time
  143. * @param $key string
  144. */
  145. Public Function Refresh ($key = "");
  146. /*
  147. * Close MySQL or memcache connection
  148. */
  149. Public function close ();
  150. /*
  151. * Delete Expired Sessions
  152. */
  153. Public function Cleanup ();
  154. }
  155. Final class Mysqlsessionengine implements sessionengine{
  156. Private $id = "";
  157. Private $storage _name= ' php_session ';
  158. Private $storage _name_slow= ' Php_session_slow ';
  159. Private $data _too_long_instead_value = ' {__data is ~ to long__} ',//if data is longer than $max _session_data_length and you is using MySQL 4 or below,insert this value into Memery table instead.
  160. Private $expire _time=1200;
  161. Private $max _session_data_length = 2048;
  162. Private $conn;
  163. Private $mysql _version;
  164. Public Function Mysqlsessionengine ($arr =array (), $key = "", &$_conn) {
  165. $this->setvariable ($arr);
  166. $this->id = $key;
  167. if (Empty ($this->id) | | strlen ($this->id)!=32) {
  168. throw new Exception (__file__. " ". __line__.": Session ' s cookie name can ' t be empty and it must has just charactors! ");
  169. }
  170. $this->conn = $_conn;
  171. if (! $this->conn| |! Is_resource ($this->conn)) {
  172. throw new Exception (__file__. " ". __line__.": Need a MySQL connection! ");
  173. }
  174. $this->mysql_version = $this->getone ("Select Floor (Version ())");
  175. if ($this->mysql_version<5) {
  176. $this->max_session_data_length = 255;
  177. }
  178. }
  179. Public Function SetVariable ($arr) {
  180. if (!empty ($arr) &&is_array ($arr)) {
  181. foreach ($arr as $k = = $v) {
  182. $this $k = $v;
  183. if ($k = = ' Storage_name ') {
  184. $this->storage_name_slow = $v. ' _slow ';
  185. }
  186. }
  187. }
  188. }
  189. Public function Get ($key = "") {
  190. if ($key = = "") $key = $this->id;
  191. $return = $this->getone (' Select value from ' $this->storage_name. ' Where id= '. $key. ');
  192. if ($return = = $this->data_too_long_instead_value)
  193. {
  194. $return = $this->getone (' Select value from ' $this->storage_name_slow. ' Where id= '. $key. ');
  195. }
  196. if (! $return)
  197. {
  198. $mysqlError = mysql_error ($this->conn);
  199. if (Strpos ($mysqlError, "doesn ' t exist")!==false)
  200. {
  201. $this->inittable ();
  202. }
  203. $return = Array ();
  204. }
  205. Else
  206. {
  207. $return = Unserialize ($return);
  208. }
  209. return $return;
  210. }
  211. Public function Close () {
  212. @mysql_close ($this->conn);
  213. }
  214. Public Function Cleanup () {
  215. if ($this->mysql_version>4) {
  216. $sql = ' Delete from '. $this->storage_name. ' Where Date_add (' time ', INTERVAL '. $this->expire_time. ' SECOND)
  217. }else{
  218. $sql = ' Delete from ' $this->storage_name_slow. ' WHERE ' time ' + '. $this->expire_time. '
  219. if ($_session[' username ']== "Leinchu") {
  220. Echo $sql;
  221. }
  222. $this->execute ($sql);
  223. $sql = ' Delete from ' $this->storage_name. ' WHERE ' time ' + '. $this->expire_time. '
  224. if ($_session[' username ']== "Leinchu") {
  225. Echo $sql;
  226. }
  227. }
  228. $this->execute ($sql);
  229. }
  230. Public Function Refresh ($key = "") {
  231. if ($this->mysql_version>4) {
  232. $sql = ' Update '. $this->storage_name. ' Set ' time ' =current_timestamp () where id= "'. $key. '";
  233. }else{
  234. $sql = ' Update '. $this->storage_name. ' Set ' time ' =unix_timestamp () where id= "'. $key. '";
  235. }
  236. $return = $this->execute ($sql);
  237. if (! $return) {
  238. $this->inittable ();
  239. $return = $this->execute ($sql, true);
  240. }
  241. return $return;
  242. }
  243. Public Function Create ($key = "", $value = "") {
  244. if ($key = = "") $key = $this->id;
  245. if ($value! = "") $value = mysql_real_escape_string (serialize ($value), $this->conn);
  246. if (strlen ($value) > $this->max_session_data_length)
  247. {
  248. if ($this->mysql_version>4) {
  249. throw new Exception (__file__. " ". __line__.": Session data is a long than max allow Length (". $this->max_session_data_length.")! ");
  250. }
  251. }
  252. if ($this->mysql_version>4) {
  253. $sql = ' replace into ' $this->storage_name. ' Set value=/'. $value. ' /', id= "'. $key. '", ' Time ' =current_timestamp () ';
  254. }else{
  255. $sql = ' replace into ' $this->storage_name. ' Set value=/'. $value. ' /', id= "'. $key. '", ' Time ' =unix_timestamp () ';
  256. }
  257. $return = $this->execute ($sql);
  258. if (! $return) {
  259. $this->inittable ();
  260. $return = $this->execute ($sql, true);
  261. }
  262. return $return;
  263. }
  264. Public function set ($key = "", $value = "") {
  265. if ($key = = "") $key = $this->id;
  266. if ($value! = "") $value = mysql_real_escape_string (serialize ($value), $this->conn);
  267. $sql = ' Update '. $this->storage_name. ' Set value=/'. $value. ' /' Where id= ' '. $key. ';
  268. if (strlen ($value) > $this->max_session_data_length)
  269. {
  270. if ($this->mysql_version>4) {
  271. throw new Exception (__file__. " ". __line__.": Session data is a long than max allow Length (". $this->max_session_data_length.")! ");
  272. }
  273. $sql = ' replace into ' $this->storage_name_slow. ' Set value=/'. $value. ' /', id= "'. $key. '", ' Time ' =unix_timestamp () ';
  274. $this->execute ($sql, true);
  275. $sql = ' Update '. $this->storage_name. ' Set value=/'. $this->data_too_long_instead_value. ' /' Where id= ' '. $key. ';
  276. }
  277. $return = $this->execute ($sql);
  278. if (! $return) {
  279. $this->inittable ();
  280. $return = $this->execute ($sql, true);
  281. }
  282. return $return;
  283. }
  284. Private Function inittable () {
  285. if ($this->mysql_version>4) {
  286. $sql = "
  287. CREATE TABLE if not exists ' ". $this->storage_name." ` (
  288. ' id ' char (+) not NULL default ' ERR ',
  289. ' Value ' VARBINARY (". $this->max_session_data_length.") Null
  290. ' Time ' timestamp not NULL for default current_timestamp on update Current_timestamp,
  291. PRIMARY KEY (' id '),
  292. KEY ' time ' (' time ')
  293. ) Engine=memory;
  294. ";
  295. }else{
  296. $sqlSlow = "
  297. CREATE TABLE if not exists ' ". $this->storage_name." _slow ' (
  298. ' id ' char (+) not NULL default ' ERR ',
  299. ' Value ' text NULL,
  300. ' Time ' int (ten) NOT null default ' 0 ',
  301. PRIMARY KEY (' id '),
  302. KEY ' time ' (' time ')
  303. ) Engine=myisam;
  304. ";
  305. $this->execute ($sqlSlow, true);
  306. $sql = "
  307. CREATE TABLE if not exists ' ". $this->storage_name." ` (
  308. ' id ' char (+) not NULL default ' ERR ',
  309. ' Value ' VARCHAR (255) NULL,
  310. ' Time ' int (ten) NOT null default ' 0 ',
  311. PRIMARY KEY (' id '),
  312. KEY ' time ' (' time ')
  313. ) Engine=memory;
  314. ";
  315. }
  316. return $this->execute ($sql, true);
  317. }
  318. Private function Execute ($sql, $die =false)
  319. {
  320. if ($die)
  321. {
  322. mysql_query ($sql, $this->conn) or Die ("EXE SQL error:
    ". Mysql_error ()."
    ". $sql.");
  323. }
  324. Else
  325. {
  326. mysql_query ($sql, $this->conn);
  327. if (Mysql_error ()) {
  328. return false;
  329. }else{
  330. return true;
  331. }
  332. }
  333. }
  334. Private Function GetOne ($sql, $die =false) {
  335. $rs = $this->query ($sql, $die);
  336. if ($rs && ($one = mysql_fetch_row ($rs))) {
  337. return $one [0];
  338. }else{
  339. return false;
  340. }
  341. }
  342. Private function Query ($sql, $die =false) {
  343. if ($die)
  344. $rs = mysql_query ($sql, $this->conn) or Die ("Query SQL error:
    ". Mysql_error ()."
    ". $sql.");
  345. Else
  346. $rs = mysql_query ($sql, $this->conn);
  347. return $rs;
  348. }
  349. }
  350. $lnk = mysql_connect (' localhost ', ' root ', ' 123456 ')
  351. Or Die (' Not connected: '. mysql_error ());
  352. Make Foo the current db
  353. mysql_select_db (' Test ', $lnk) or Die (' can/' t use foo: '. mysql_error ());
  354. $S = new session ($LNK);
  355. if (! $S->last) {
  356. $S->last = time ();
  357. }
  358. echo "First visit at". $S->last. "
    ";
  359. if (! $S->lastv) {
  360. $S->lastv = 0;
  361. }
  362. $S->lastv++;
  363. echo "lastv=". $S->lastv. "
    ";
  364. echo "test=". $S->test. "
    ";
  365. if (Isset ($_get[' Max ')) {
  366. $S->boom = str_repeat ("OK", 255);
  367. }
  368. if (isset ($_get[' boom ')) {
  369. $S->boom = $_get[' boom ');
  370. }
  371. echo "boom=". $S->boom. "
    ";
  372. ?>
Copy Code
  • 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.