Methods for writing session data to the database in php

Source: Internet
Author: User
Methods for writing session data to the database in php

  1. Create database 'session ';

Create a table structure:

  1. Create table 'session '(id CHAR (30) not null, 'user' CHAR (30), data CHAR (3000), parmiry by ('id '));

Save the session file session_start.php:

  1. $ Con = mysql_connection ("127.0.0.1", "user", "pass ");
  2. Mysql_select_db ("session ");
  3. Function open ($ save_path, $ session_name)
  4. {
  5. Return (true );
  6. }
  7. Function close ()
  8. {
  9. Return (true );
  10. }
  11. Function read ($ id)
  12. {
  13. If ($ result = mysql_query ("SELECT * FROM session WHERE id = '$ ID '"))
  14. {
  15. If ($ row = mysql_felth_row ($ result ))
  16. {Return $ row ["data"];}
  17. }
  18. Else
  19. {
  20. Return "";
  21. }
  22. }
  23. Function write ($ id, $ sess_data)
  24. {
  25. If ($ result = mysql_query ("UPDATE session SET data = '$ sess_data' WHERE id = '$ ID '"))
  26. {
  27. Return true;
  28. }
  29. Else
  30. {
  31. Return false;
  32. }
  33. }
  34. Function destroy ($ id)
  35. {
  36. If ($ result = mysql_query ("DELETE * FROM session WHERE id = '$ ID '"))
  37. {
  38. Return true;
  39. }
  40. Else
  41. {
  42. Return false;
  43. }
  44. }
  45. /*************************************** ******
  46. * WARNING-You will need to implement some *
  47. * Sort of garbage collection routine here .*
  48. **************************************** *****/
  49. Function gc ($ maxlifetime)
  50. {
  51. Return true;
  52. }
  53. Session_set_save_handler ("open", "close", "read", "write", "destroy", "gc ");
  54. Session_start ();
  55. // Proceed to use sessions normally
  56. ?>

Usage: on the page where you need to save the session to the database, introduce the file session_user_start.php. Note that this file must be in the first line of the file.

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.