A class that replaces phpsession with a mysql memory table-php Tutorial

Source: Internet
Author: User
Tags key string sql error
A class that replaces phpsession with a mysql memory table

  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; // The default value is 180 minutes, which is too long and 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 are 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 have just 32 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) } Else {
  217. $ SQL = 'delete from'. $ this-> storage_name_slow. 'where 'time' + '. $ this-> expire_time .' If ($ _ SESSION ['username'] = "leinchu "){
  218. Echo $ SQL;
  219. }
  220. $ This-> execute ($ SQL );
  221. $ SQL = 'delete from'. $ this-> storage_name. 'where 'time' + '. $ this-> expire_time .' If ($ _ SESSION ['username'] = "leinchu "){
  222. Echo $ SQL;
  223. }
  224. }
  225. $ This-> execute ($ SQL );
  226. }
  227. Public function refresh ($ key = ""){
  228. If ($ this-> mysql_version> 4 ){
  229. $ SQL = 'update'. $ this-> storage_name. 'set'time' = CURRENT_TIMESTAMP () where id = "'. $ key .'"';
  230. } Else {
  231. $ SQL = 'update'. $ this-> storage_name. 'set'time' = unix_timestamp () where id = "'. $ key .'"';
  232. }
  233. $ Return = $ this-> execute ($ SQL );
  234. If (! $ Return ){
  235. $ This-> initTable ();
  236. $ Return = $ this-> execute ($ SQL, true );
  237. }
  238. Return $ return;
  239. }
  240. Public function create ($ key = "", $ value = ""){
  241. If ($ key = "") $ key = $ this-> id;
  242. If ($ value! = "") $ Value = mysql_real_escape_string (serialize ($ value), $ this-> conn );
  243. If (strlen ($ value)> $ this-> max_session_data_length)
  244. {
  245. If ($ this-> mysql_version> 4 ){
  246. Throw new Exception (_ FILE __. "-> ". _ LINE __. ": Session data is long than max allow length (". $ this-> max_session_data_length. ")! ");
  247. }
  248. }
  249. If ($ this-> mysql_version> 4 ){
  250. $ SQL = 'replace '. $ this-> storage_name. 'set value = /''. $ value. '/', id = "'. $ key. '", 'Time' = CURRENT_TIMESTAMP ()';
  251. } Else {
  252. $ SQL = 'replace '. $ this-> storage_name. 'set value = /''. $ value. '/', id = "'. $ key. '", 'Time' = unix_timestamp ()';
  253. }
  254. $ Return = $ this-> execute ($ SQL );
  255. If (! $ Return ){
  256. $ This-> initTable ();
  257. $ Return = $ this-> execute ($ SQL, true );
  258. }
  259. Return $ return;
  260. }
  261. Public function set ($ key = "", $ value = ""){
  262. If ($ key = "") $ key = $ this-> id;
  263. If ($ value! = "") $ Value = mysql_real_escape_string (serialize ($ value), $ this-> conn );
  264. $ SQL = 'update'. $ this-> storage_name. 'set value =/'. $ value.'/'Where id = "'. $ key .'"';
  265. If (strlen ($ value)> $ this-> max_session_data_length)
  266. {
  267. If ($ this-> mysql_version> 4 ){
  268. Throw new Exception (_ FILE __. "-> ". _ LINE __. ": Session data is long than max allow length (". $ this-> max_session_data_length. ")! ");
  269. }
  270. $ SQL = 'replace '. $ this-> storage_name_slow. 'set value = /''. $ value. '/', id = "'. $ key. '", 'Time' = unix_timestamp ()';
  271. $ This-> execute ($ SQL, true );
  272. $ SQL = 'update '. $ this-> storage_name. 'set value = /''. $ this-> data_too_long_instead_value. '/'Where id = "'. $ key. '"';
  273. }
  274. $ Return = $ this-> execute ($ SQL );
  275. If (! $ Return ){
  276. $ This-> initTable ();
  277. $ Return = $ this-> execute ($ SQL, true );
  278. }
  279. Return $ return;
  280. }
  281. Private function initTable (){
  282. If ($ this-> mysql_version> 4 ){
  283. $ SQL ="
  284. Create table if not exists "'. $ this-> storage_name ."'(
  285. 'Id' char (32) not null default 'err ',
  286. 'Value' VARBINARY (". $ this-> max_session_data_length.") NULL,
  287. 'Time' timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  288. Primary key ('id '),
  289. KEY 'time' ('time ')
  290. ) ENGINE = MEMORY;
  291. ";
  292. } Else {
  293. $ SqlSlow ="
  294. Create table if not exists "'. $ this-> storage_name." _ slow '(
  295. 'Id' char (32) not null default 'err ',
  296. 'Value' text NULL,
  297. 'Time' int (10) not null default '0 ',
  298. Primary key ('id '),
  299. KEY 'time' ('time ')
  300. ) ENGINE = MyISAM;
  301. ";
  302. $ This-> execute ($ sqlSlow, true );
  303. $ SQL ="
  304. Create table if not exists "'. $ this-> storage_name ."'(
  305. 'Id' char (32) not null default 'err ',
  306. 'Value' VARCHAR (255) NULL,
  307. 'Time' int (10) not null default '0 ',
  308. Primary key ('id '),
  309. KEY 'time' ('time ')
  310. ) ENGINE = MEMORY;
  311. ";
  312. }
  313. Return $ this-> execute ($ SQL, true );
  314. }
  315. Private function execute ($ SQL, $ die = false)
  316. {
  317. If ($ die)
  318. {
  319. Mysql_query ($ SQL, $ this-> conn) or die ("exe SQL error:
    ". Mysql_error ()."
    ". $ SQL ."");
  320. }
  321. Else
  322. {
  323. Mysql_query ($ SQL, $ this-> conn );
  324. If (mysql_error ()){
  325. Return false;
  326. } Else {
  327. Return true;
  328. }
  329. }
  330. }
  331. Private function getOne ($ SQL, $ die = false ){
  332. $ Rs = $ this-> query ($ SQL, $ die );
  333. If ($ rs & ($ one = mysql_fetch_row ($ rs ))){
  334. Return $ one [0];
  335. } Else {
  336. Return false;
  337. }
  338. }
  339. Private function query ($ SQL, $ die = false ){
  340. If ($ die)
  341. $ Rs = mysql_query ($ SQL, $ this-> conn) or die ("query SQL error:
    ". Mysql_error ()."
    ". $ SQL ."");
  342. Else
  343. $ Rs = mysql_query ($ SQL, $ this-> conn );
  344. Return $ rs;
  345. }
  346. }
  347. $ Lnk = mysql_connect ('localhost', 'root', '123 ')
  348. Or die ('not ccted: '. mysql_error ());
  349. // Make foo the current db
  350. Mysql_select_db ('test', $ lnk) or die ('Can/'t use foo: '. mysql_error ());
  351. $ S = new session ($ lnk );
  352. If (! $ S-> last ){
  353. $ S-> last = time ();
  354. }
  355. Echo "First visit at". $ S-> last ."
    ";
  356. If (! $ S-> lastv ){
  357. $ S-> lastv = 0;
  358. }
  359. $ S-> lastv ++;
  360. Echo "lastv =". $ S-> lastv ."
    ";
  361. Echo "test =". $ S-> test ."
    ";
  362. If (isset ($ _ GET ['Max ']) {
  363. $ S-> boom = str_repeat ("OK", 255 );
  364. }
  365. If (isset ($ _ GET ['boom ']) {
  366. $ S-> boom = $ _ GET ['boom '];
  367. }
  368. Echo "boom =". $ S-> boom ."
    ";
  369. ?>

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.