Witaj Gościu! ( Zaloguj | Rejestruj )

Forum PHP.pl

> Session handler, Czy opłaca się trzymać osobno zmienne?
Prph
post
Post #1





Grupa: Zarejestrowani
Postów: 338
Pomógł: 2
Dołączył: 4.03.2006
Skąd: Łódź

Ostrzeżenie: (0%)
-----


Witam,

W PHP5 zaawansowane programowanie autorzy przedstawili mechanizm obslugi sesji, ktory trzymal zmienne w osobnej tabeli. Dzieki tezmu wydajnosc miala nieco wzrosnac.

Takie rozwiazanie jednak ma pewna wade - zmienne pobierane za z sesji poprzez metody __get i __set, nie zaś $_SESSION['zmienna'];

W chwili obecnie przysparza mi to więcej problemów niż mogłem to sobie wyobrazić.

Jak Wy organizujecie session handlera? Jest sens dzielenia sesji na zmienne i info o sesji?

Pozdrawiam,
Adrian.
Go to the top of the page
+Quote Post
 
Start new topic
Odpowiedzi
Prph
post
Post #2





Grupa: Zarejestrowani
Postów: 338
Pomógł: 2
Dołączył: 4.03.2006
Skąd: Łódź

Ostrzeżenie: (0%)
-----


Doskonale Cię rozumiem, ale ja ostatnio non stop siedze i czytam (IMG:http://forum.php.pl/style_emoticons/default/winksmiley.jpg)
Nie miałbym problemów, jakbym sie nie uczepił rozwiązania przedstawionego w książce PHP5, Zaawansowane programowanie. Nadal uważam, że jest ono dobre, ale troche zakręcone.

Napisałem więc raczej prosty session handler. Lekkie modyfikacje, zeby był wygodniejszy. Kod poniżej:

  1. <?php
  2.  
  3. class NotLoggedInSessionException extends Exception
  4. {
  5. }
  6.  
  7. class Session
  8. {
  9. private $_oDatabase;
  10.  
  11. private static $_oInstance;
  12.  
  13. private $_sPHPSessionId;
  14. private $_iNativeSessionId;
  15. private $_iSessionLifespan = 3600;
  16. private $_iSessionTimeout = 60;
  17.  
  18. private $_iUserId;
  19. private $_bIsLoggedIn;
  20.  
  21. private function __construct()
  22. {
  23. $this->_oDatabase = Database::getInstance();
  24. $this->_bIsLoggedIn = false;
  25.  
  26. (
  27. array(&$this, '_sessionOpen'),
  28. array(&$this, '_sessionClose'),
  29. array(&$this, '_sessionRead'),
  30. array(&$this, '_sessionWrite'),
  31. array(&$this, '_sessionDestroy'),
  32. array(&$this, '_sessionGC')
  33. );
  34.  
  35. try
  36. {
  37. $this->_sessionGC();
  38. $this->_checkForActiveSession();
  39. }
  40. catch (Exception $oException)
  41. {
  42. throw $oException;
  43. }
  44.  
  45. session_set_cookie_params($this->_iSessionLifespan);
  46. }
  47.  
  48. public static function getInstance()
  49. {
  50. if(!isset(self::$_oInstance))
  51. {
  52. $sClassName = __CLASS__;
  53. self::$_oInstance = new $sClassName;
  54. }
  55.  
  56. return self::$_oInstance;
  57. }
  58.  
  59. public function _sessionOpen($sSavePath, $sSessionName)
  60. {
  61. return true;
  62. }
  63.  
  64. public function _sessionRead($sPHPSessionId)
  65. {
  66. try
  67. {
  68. if(!$this->_isSession())
  69. $this->_createNewSession($sPHPSessionId);
  70.  
  71. $sQuery = 'SELECT id, logged_in, user_id, vars
  72.  FROM session
  73.  WHERE phpsessid = "'.$sPHPSessionId.'"';
  74.  
  75. $this->_oDatabase->query($sQuery);
  76.  
  77. $aRow = $this->_oDatabase->fetch();
  78.  
  79. $this->_iNativeSessionId = $aRow['id'];
  80. $this->_bLoggedIn = $aRow['logged_in'];
  81. $this->_iUserId = $aRow['user_id'];
  82. }
  83. catch (Exception $oException)
  84. {
  85. throw $oException;
  86. }
  87.  
  88. return $aRow['vars'];
  89. }
  90.  
  91. public function _sessionWrite($sPHPSessionId, $sData)
  92. {
  93. $aToUpdate[] = array('vars', $sData);
  94.  
  95. try
  96. {
  97. $this->_oDatabase->update('session', $aToUpdate, 'phpsessid = "'.$this->_sPHPSessionId.'"');
  98. }
  99. catch (Exception $oException)
  100. {
  101. return false;
  102. }
  103.  
  104. return true;
  105. }
  106.  
  107. public function _sessionDestroy($sPHPSessionId)
  108. {
  109. $sQuery = 'DELETE FROM session
  110.  WHERE phpsessid = "'.$sPHPSessionId.'"';
  111.  
  112. try
  113. {
  114. $this->_oDatabase->query($sQuery);
  115. }
  116. catch (Exception $oException)
  117. {
  118.  throw $oException;
  119. }
  120.  
  121. return true;
  122. }
  123.  
  124. public function _sessionGC($iMaxLifeTime = null)
  125. {
  126.  
  127. $sQuery = 'DELETE FROM session
  128.  WHERE
  129.  ((now() - start) > '.$this->_iSessionLifespan.') OR
  130.  ((now() - last_activity) > '.$this->_iSessionTimeout.')';
  131.  
  132. try
  133. {
  134. $this->_oDatabase->query($sQuery);
  135. }
  136. catch (Exception $oException)
  137. {
  138.  throw $oException;
  139. }
  140.  
  141. return true;
  142. }
  143.  
  144. public function _sessionClose()
  145. {
  146. return true;
  147. }
  148.  
  149. private function _updateSession()
  150. {
  151. if(isset($this->_iNativeSessionId))
  152. {
  153. $aToUpdate[] = array('last_activity', 'now()', false);
  154.  
  155. try
  156. {
  157. $this->_oDatabase->update('session', $aToUpdate, 'id = "'.$this->_iNativeSessionId.'"');
  158. }
  159. catch (Exception $oException)
  160. {
  161. throw $oException;
  162. }
  163. }
  164. }
  165.  
  166. private function _isSession()
  167. {
  168. if(isset($this->_iNativeSessionId))
  169. return true;
  170. else
  171. return false;
  172. }
  173.  
  174. private function _createNewSession($sPHPSessionId)
  175. {
  176. $sUserAgent = $_SERVER['HTTP_USER_AGENT'];
  177.  
  178. $aToInsert[] = array('phpsessid', $sPHPSessionId);
  179. $aToInsert[] = array('start', 'now()', false);
  180. $aToInsert[] = array('user_agent', $sUserAgent);
  181.  
  182. try
  183. {
  184. $this->_oDatabase->insert('session', $aToInsert);
  185.  
  186. $sQuery = 'SELECT id FROM session WHERE phpsessid = "'.$this->_sPHPSessionId.'"';
  187. $this->_oDatabase->query($sQuery);
  188.  
  189. $aRow = $this->_oDatabase->fetch();
  190. $this->_iNativeSessionId = $aRow['id'];
  191.  
  192. $this->_sPHPSessionId = $sPHPSessionId;
  193. }
  194. catch (Exception $oException)
  195. {
  196.  throw $oException;
  197. }
  198. }
  199.  
  200. private function _checkForActiveSession()
  201. {
  202. $sUserAgent = $_SERVER['HTTP_USER_AGENT'];
  203.  
  204. if(!empty($_COOKIE['PHPSESSID']))
  205. {
  206. $this->_sPHPSessionId = $_COOKIE['PHPSESSID'];
  207.  
  208. $sQuery = 'SELECT id
  209.  FROM session
  210.  WHERE
  211.  phpsessid = "'.$this->_sPHPSessionId.'" AND
  212.  (
  213.  (now() - start) < '.$this->_iSessionLifespan.' AND
  214.  user_agent = "'.$sUserAgent.'" AND
  215.  (now() - last_activity) <= '.$this->_iSessionTimeout.'
  216.  ) OR
  217.  last_activity IS NULL';
  218.  
  219. try
  220. {
  221. $this->_oDatabase->query($sQuery);
  222.  
  223. if($this->_oDatabase->numRows() === 0)
  224. {
  225. unset($_COOKIE['PHPSESSID']); // session is not valid or actual
  226. }
  227. else
  228. {
  229. $aRow = $this->_oDatabase->fetch();
  230. $this->_iNativeSessionId = $aRow['id'];
  231. $this->_updateSession();
  232. }
  233. }
  234. catch (Exception $oException)
  235. {
  236. throw $oException;
  237. }
  238. }
  239. }
  240.  
  241. public function isLoggedIn()
  242. {
  243. return $this->_bIsLoggedIn;
  244. }
  245.  
  246. public function getUserId()
  247. {
  248. if($this->isLoggedIn())
  249. return $this->_iUserId;
  250. }
  251.  
  252. public function getUserObject()
  253. {
  254. if($this->isLoggedIn())
  255. {
  256. try
  257. {
  258.  $oUser = new User($this->getUserId());
  259.  return $oUser;
  260. }
  261. catch (Exception $oException)
  262. {
  263. throw $oException;
  264. }
  265. }
  266. else
  267. throw new SessionException('Can not return object. User was not logged in');
  268. }
  269.  
  270. public function login($sLogin, $sPlainPassword)
  271. {
  272. $sPassword = md5($sPlainPassword);
  273.  
  274. $sQuery = 'SELECT id FROM users
  275.  WHERE
  276.  login = "'.$sLogin.'" AND
  277.  password = "'.$sPassword.'"';
  278.  
  279. try
  280. {
  281. $this->_oDatabase->query($sQuery);
  282. if($this->_oDatabase->numRows() == 1)
  283. {
  284. $aUser = $this->_oDatabase->fetch();
  285. $this->_iUserId = $aUser['id'];
  286.  
  287. $aToUodate[] = array('logged_in', 'true');
  288. $aToUodate[] = array('user_id', $this->_iUserId);
  289.  
  290. $this->_oDatabase->update('session', $aToUodate, 'id = "'.$this->_iNativeSessionId.'"');
  291.  
  292. $this->_bIsLoggedIn = true;
  293.  
  294. return true;
  295. }
  296. }
  297. catch (Exception $oException)
  298. {
  299.  throw $oException;
  300. }
  301. }
  302.  
  303. public static function logout()
  304. {
  305. if($this->isLoggedIn())
  306. {
  307. $aToUodate[] = array('logged_in', false);
  308. $aToUodate[] = array('user_id', 0);
  309.  
  310. try
  311. {
  312. $this->_oDatabase->update('session', $aToUodate, 'id = "'.$this->_iNativeSessionId.'"');
  313.  
  314. $this->_bIsLoggedIn = false;
  315. return true;
  316. }
  317. catch (Exception $oException)
  318. {
  319.  throw $oException;
  320. }
  321. }
  322. }
  323. }
  324. ?>


Przepraszam, że bez komentarzy, ale zamieszczam opis metod:

Konstruktor: sprząta stare sesje. Wywoluje metodę _checkForActivesession a następnie uruchamia sesję.

_checkForActivesession: sprawdza, czy użytkownik jest w trakcje sesji - na podstawie ciasteczka. Pobiera id sesji z ciastka i sprawdza w bazie czy jest jeszcze prawdziwa. Jezeli nie, usuwa ciastko. Jezeli sesja jest poprawna - odswieza jej czas metoda _updateSession.

_sessionRead: wywoływana przez php. Sprawdza czy, jest sesja (jeżeli poprzednia metoda stwierdziała, że sesja jest poprawna, to także ustawiła id sesji). Jeżeli nie - tworzy nową za pomocą metody _createNewSession. Dalej pobiera dane sesji z bazy, ustawia id uzytkownika i inne dane, a następnie zwraca zmienne sesji.

_sessionWrite: zapisauje zmienne sesji w bazie.

login, logout, getUserObject to dodane przeze mnie metody, aby łatwiej zarządzać sesją (IMG:http://forum.php.pl/style_emoticons/default/winksmiley.jpg)

CZekam na Wasze komentarze.
Pozdrawiam, Adrian.
Go to the top of the page
+Quote Post

Posty w temacie


Reply to this topicStart new topic
2 Użytkowników czyta ten temat (2 Gości i 0 Anonimowych użytkowników)
0 Zarejestrowanych:

 



RSS Aktualny czas: 14.10.2025 - 07:26