php将session保存到数据库的简单示例

前端之家收集整理的这篇文章主要介绍了php将session保存到数据库的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
PHP中将session保存到数据库代码感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!
我们可以使用session_set_save_handler()来注册连接数据的函数。下面是完整的演示代码
  1. /**
  2. * PHP中将session保存到数据库代码
  3. *
  4. * @param
  5. * @arrange 512-笔记网: 512Pic.com
  6. **/
  7. // 'sessions' table schema
  8. // create table sessions (
  9. // session_id char(32) not null,// session_data text not null,// session_expiration int(11) unsigned not null,// primary key (session_id));
  10. //
  11. include_once 'DB.PHP';
  12. // Global Variables
  13. $dbh = NULL;
  14. function on_session_start ($save_path,$session_name) {
  15. global $dbh;
  16. $dbh = DB::connect('MysqL://user:secret@localhost/SITE_SESSIONS',true);
  17. if (DB::isError($dbh)) {
  18. die(sprintf('Error [%d]: %s',$dbh->getCode(),$dbh->getMessage()));
  19. }
  20. }
  21. function on_session_end ()
  22. {
  23. // Nothing needs to be done in this function
  24. // since we used persistent connection.
  25. }
  26. function on_session_read ($key)
  27. {
  28. global $dbh;
  29. $stmt = "select session_data from sessions";
  30. $stmt .= " where session_id = '$key'";
  31. $stmt .= " and session_expiration > now()";
  32. $sth = $dbh->query($sth);
  33. $row = $sth->fetchRow(DB_FETCHMODE_ASSOC);
  34. return $row['session_data'];
  35. }
  36. function on_session_write ($key,$val)
  37. {
  38. global $dbh;
  39. $val = addslashes($val);
  40. $insert_stmt = "insert into sessions values('$key','$val',now() + 3600)";
  41. $update_stmt = "update sessions set session_data = '$val',";
  42. $update_stmt .= "session_expiration = now() + 3600 ";
  43. $update_stmt .= "where session_id = '$key'";
  44. // First we try to insert,if that doesn't succeed,it means
  45. // session is already in the table and we try to update
  46. if (DB::isError($dbh->query($insert_stmt)))
  47. $dbh->query($update_stmt);
  48. }
  49. function on_session_destroy ($key)
  50. {
  51. global $dbh;
  52. $stmt = "delete from sessions where session_id = '$key'";
  53. $dbh->query($stmt);
  54. }
  55. function on_session_gc ($max_lifetime)
  56. {
  57. global $dbh;
  58. // In this example,we don't use $max_lifetime parameter
  59. // We simply delete all sessions that have expired
  60. $stmt = "delete from sessions where session_expiration < now()";
  61. $dbh->query($stmt);
  62. }
  63. session_start ();
  64. // Register the $counter variable as part
  65. // of the session
  66. session_register ("counter");
  67. // Set the save handlers
  68. session_set_save_handler ("on_session_start","on_session_end","on_session_read","on_session_write","on_session_destroy","on_session_gc");
  69. // Let's see what it does
  70. $counter++;
  71. print $counter;
  72. session_destroy();
  73. /*** 来自编程之家 jb51.cc(jb51.cc) ***/

 

猜你在找的PHP相关文章