DatabaseSessionHandler.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. namespace Elgg\Http;
  3. /**
  4. * Database session handler
  5. *
  6. * @access private
  7. *
  8. * @package Elgg.Core
  9. * @subpackage Http
  10. */
  11. class DatabaseSessionHandler implements \SessionHandlerInterface {
  12. /** @var \Elgg\Database $db */
  13. protected $db;
  14. /**
  15. * Constructor
  16. *
  17. * @param \Elgg\Database $db The database
  18. */
  19. public function __construct(\Elgg\Database $db) {
  20. $this->db = $db;
  21. }
  22. /**
  23. * {@inheritDoc}
  24. */
  25. public function open($save_path, $name) {
  26. return true;
  27. }
  28. /**
  29. * {@inheritDoc}
  30. */
  31. public function read($session_id) {
  32. $id = sanitize_string($session_id);
  33. $query = "SELECT * FROM {$this->db->getTablePrefix()}users_sessions WHERE session='$id'";
  34. $result = $this->db->getDataRow($query);
  35. if ($result) {
  36. return (string) $result->data;
  37. } else {
  38. return false;
  39. }
  40. }
  41. /**
  42. * {@inheritDoc}
  43. */
  44. public function write($session_id, $session_data) {
  45. $id = sanitize_string($session_id);
  46. $time = time();
  47. $sess_data_sanitised = sanitize_string($session_data);
  48. $query = "REPLACE INTO {$this->db->getTablePrefix()}users_sessions
  49. (session, ts, data) VALUES
  50. ('$id', '$time', '$sess_data_sanitised')";
  51. if ($this->db->insertData($query) !== false) {
  52. return true;
  53. } else {
  54. return false;
  55. }
  56. }
  57. /**
  58. * {@inheritDoc}
  59. */
  60. public function close() {
  61. return true;
  62. }
  63. /**
  64. * {@inheritDoc}
  65. */
  66. public function destroy($session_id) {
  67. $id = sanitize_string($session_id);
  68. $query = "DELETE FROM {$this->db->getTablePrefix()}users_sessions WHERE session='$id'";
  69. return (bool) $this->db->deleteData($query);
  70. }
  71. /**
  72. * {@inheritDoc}
  73. */
  74. public function gc($max_lifetime) {
  75. $life = time() - $max_lifetime;
  76. $query = "DELETE FROM {$this->db->getTablePrefix()}users_sessions WHERE ts < '$life'";
  77. return (bool) $this->db->deleteData($query);
  78. }
  79. }