login  Naam:   Wachtwoord: 
Registreer je!
 Scripts:

Scripts > PHP > Beveiliging > Custom database-sessiehandler

Custom database-sessiehandler

Auteur: ArieMedia - 27 juni 2011 - 17:28 - Gekeurd door: Joel - Hits: 3348 - Aantal punten: (0 stemmen)




---
- VOORWOORD
---
Je zal misschien denken, waarom ?! $_SESSION['blaat'] werkt toch ook?
Dat klopt, maar deze klasse zorgt ervoor dat je sessies in de database worden opgeslagen. Het grote voordeel hiervan is dat je niet met problemen van shared hosting zit. Er bestaat ook een variant om sessies alsnog in de database op te slaan PHP.net: session_set_save_handler. Maar omdat globals vanuit den boze zijn in OO wereld, dus deze klasse

---
- INSTALLATIE
---

1] Download, en zet het script ergens op je site
2] Voeg ondestaande SQL uit in je Phpmyadmin (of andere databasetool)
3] Include het script waar je hem nodig hebt (bijv index.php), zorg ervoor dat je al een databaseconnectie hebt lopen
4] Bekijk de voorbeeldcode

SQL
  1. --
  2. -- Tabelstructuur voor tabel `sessies`
  3. --
  4.  
  5. CREATE TABLE IF NOT EXISTS `sessies` (
  6. `naam` varchar(255) NOT NULL,
  7. `gestart_op` datetime NOT NULL,
  8. `laatste_actie` datetime NOT NULL,
  9. `expires` int(11) NOT NULL,
  10. UNIQUE KEY `naam` (`naam`)
  11. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
  12.  
  13. --
  14. -- Tabelstructuur voor tabel `sessies_data`
  15. --
  16.  
  17. CREATE TABLE IF NOT EXISTS `sessies_data` (
  18. `sessid` varchar(255) NOT NULL,
  19. `sessnaam` varchar(255) NOT NULL,
  20. `sessdata` text NOT NULL
  21. ) ENGINE=MyISAM DEFAULT CHARSET=latin1;



---
- VOORBEELDCODE
---

index.php
  1. <?php
  2. require_once 'sessie.class.php';
  3.  
  4. mysql_connect('localhost', 'sesstest', 'sessie');
  5. mysql_select_db('sesstest');
  6.  
  7. try {
  8. $sessie = new DBsession();
  9. $sessie->setSession('naam', 'Arjan');
  10.  
  11. echo 'Hallo, volgensmij heet jij '.$sessie->getSession('naam');
  12. }
  13.  
  14. catch(Exception $e) {
  15. echo $e->getMessage();
  16. }
  17. ?>


---
- BUGS
---
Graag een mailtje of een bericht hier op Sitemasters, een bug hier betekend een veiligheidslek bij iedereen die dit script gebruikt.

---
- NAWOORD
---

Voor degene die met adoDB werken, daar heb ik ook een versie voor klaarliggen.
Graag onderbouwde kritiek, anders heeft niemand er wat aan.

Code:
  1. <?php
  2. /**
  3.  * DBsession
  4.  * custom method to make sessions
  5.  * this class uses sessions wich are set in a database
  6.  *
  7.  * @author: Arjan Veldkamp <arjan@arjanv.nl>
  8.  * @date: 27/06/2011
  9.  */
  10. class DBsession {
  11.  
  12. /**
  13. * How long a session should exist
  14. **/
  15. public $lifetime = 3600;
  16.  
  17. private $_sessie;
  18. private $_sessiedb = 'sessies';
  19. private $_sessiondatadb = 'sessies_data';
  20.  
  21. protected $secret;
  22. protected $sessiondata = array();
  23.  
  24. public function __construct() {
  25. $_SESSION = array();
  26. $this->secret = sha1(md5('mySecreyKey'));
  27. $this->prepareSession();
  28. }
  29.  
  30. /**
  31. * Check if we need to update or create a new session
  32. */
  33.  
  34. public function prepareSession() {
  35. if(!isset($_COOKIE[$this->secret])) {
  36. $this->_startSession();
  37. } else {
  38. $this->_extendSession();
  39. }
  40.  
  41. $this->_getSessionData();
  42. }
  43.  
  44. /**
  45. * Start a new session, the user has not been here before, or the old session has been expired
  46. *
  47. * We will put a cookie on the user's machine with a key, this key gives access to the data assigned to this cookie
  48. */
  49.  
  50. protected function _startSession() {
  51. $exptime = time() + $this->lifetime;
  52. $sessname = $this->_createSessionName();
  53. setcookie($this->secret, $sessname, $exptime);
  54. $sql = 'INSERT INTO '.$this->_sessiedb.'
  55. (naam, gestart_op, laatste_actie, expires)
  56. VALUES("'.$sessname.'", NOW(), NOW(), '.$exptime.')';
  57. if(!mysql_query($sql)) {
  58. setcookie($this->secret, $sessname, time() - 3600);
  59. throw new Exception('Er trad een fout op tijdens het maken van een sessiekey', 2);
  60. }
  61.  
  62. $this->_sessie = $sessname;
  63. }
  64.  
  65. /**
  66. * This user has been here before within the given lifetime of the session
  67. *
  68. * We are gonna extend the cookie with the given lifetime
  69. */
  70.  
  71. protected function _extendSession() {
  72. $exptime = time() + $this->lifetime;
  73. $this->_sessie = $_COOKIE[$this->secret];
  74. setcookie($this->secret, $this->_sessie, $exptime);
  75. $sql = 'SELECT naam
  76. FROM '.$this->_sessiedb.'
  77. WHERE naam = "'.$this->_sessie.'"
  78. AND expires > '.time();
  79. $rs = mysql_query($sql);
  80. if(mysql_num_rows($rs) == 1) {
  81. $sql = 'UPDATE '.$this->_sessiedb.'
  82. SET expires = '.$exptime.',
  83. laatste_actie = NOW()
  84. WHERE naam = "'.$this->_sessie.'"';
  85.  
  86. if(!mysql_query($sql)) {
  87. throw new Exception('Er trad een fout op tijdens het verlengen van de sessiekey', 2);
  88. }
  89. } else {
  90. $this->_startSession();
  91. }
  92.  
  93. }
  94.  
  95. /**
  96. * Get all session-data wich fits with the sessionkey
  97. * The sessionkey connects the browser with the sessiondata
  98. */
  99.  
  100. protected function _getSessionData() {
  101. $sql = 'SELECT sessnaam, sessdata
  102. FROM '.$this->_sessiondatadb.'
  103. WHERE sessid = "'.$this->_sessie.'"';
  104. $rs = mysql_query($sql);
  105. if(mysql_num_rows($rs) > 0) {
  106. while($row = mysql_fetch_assoc($rs)) {
  107. $this->sessiondata[$row['sessnaam']] = $row['sessdata'];
  108. }
  109. }
  110. }
  111.  
  112. /**
  113. * Get the session
  114. */
  115.  
  116. public function getSession($key) {
  117. if(array_key_exists($key, $this->sessiondata)) {
  118. return $this->sessiondata[$key];
  119. }
  120.  
  121. return false;
  122. }
  123.  
  124. /**
  125. * Set a new session variable
  126. * @param string - session-name
  127. * @param mixed - the session's value
  128. *
  129. * When the session-name allready exists, update it with the new value
  130. */
  131.  
  132. public function setSession($naam, $val='') {
  133. if(!array_key_exists($naam, $this->sessiondata)) {
  134. $sql = 'INSERT INTO '.$this->_sessiondatadb.'
  135. (sessid, sessnaam, sessdata)
  136. VALUES( "'.$this->_sessie.'", "'.$naam.'", "'.$val.'")';
  137. if(!mysql_query($sql)) {
  138. throw new Exception('Er is een fout opgetreden tijdens het maken van een sessie');
  139. }
  140. } else {
  141. $sql = 'UPDATE '.$this->_sessiondatadb.'
  142. SET sessdata = "'.$val.'"
  143. WHERE sessid = "'.$this->_sessie.'" AND sessnaam = "'.$naam.'"';
  144. if(!mysql_query($sql)) {
  145. throw new Exception('Er is een fout opgetreden tijdens het updaten van een sessie');
  146. }
  147. }
  148.  
  149. $this->sessiondata[$naam] = $val;
  150. return true;
  151. }
  152.  
  153. /**
  154. * Delete a session
  155. * @param string - session wich you would like to destroy
  156. * @return void
  157. */
  158.  
  159. public function deleteSession($naam) {
  160. if(array_key_exists($naam, $this->sessiondata)) {
  161. unset($this->sessiondata[$naam]);
  162. $sql = 'DELETE FROM '.$this->_sessiondatadb.'
  163. WHERE sessid = "'.$this->_sessie.'" AND sessnaam = "'.$naam.'"';
  164.  
  165. mysql_query($sql);
  166. }
  167. }
  168.  
  169. /**
  170. * Create a unique id
  171. */
  172.  
  173. protected function _createSessionName() {
  174. return md5(uniqid());
  175. }
  176. }
  177. ?>
Download code! Download code (.txt)

 Stemmen
Niet ingelogd.

 Reacties
Post een reactie
Lees de reacties (8)
© 2002-2024 Sitemasters.be - Regels - Laadtijd: 0.044s