SessionHandler.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. <?php
  2. require 'SharedConfigurations.php';
  3. // This example demonstrates how to leverage Predis to save PHP sessions on Redis.
  4. //
  5. // The value of `session.gc_maxlifetime` in `php.ini` will be used by default as the
  6. // the TTL for keys holding session data on Redis, but this value can be overridden
  7. // when creating the session handler instance with the `gc_maxlifetime` option.
  8. //
  9. // Note that this class needs PHP >= 5.4 but can be used on PHP 5.3 if a polyfill for
  10. // SessionHandlerInterface (see http://www.php.net/class.sessionhandlerinterface.php)
  11. // is provided either by you or an external package like `symfony/http-foundation`.
  12. if (!interface_exists('SessionHandlerInterface')) {
  13. die("ATTENTION: the session handler implemented by Predis needs PHP >= 5.4.0 or a polyfill ".
  14. "for \SessionHandlerInterface either provided by you or an external package.\n");
  15. }
  16. // Instantiate a new client just like you would normally do. We'll prefix our session keys here.
  17. $client = new Predis\Client($single_server, array('prefix' => 'sessions:'));
  18. // Set `gc_maxlifetime` so that a session will be expired after 5 seconds since last access.
  19. $handler = new Predis\Session\SessionHandler($client, array('gc_maxlifetime' => 5));
  20. // Register our session handler (it uses `session_set_save_handler()` internally).
  21. $handler->register();
  22. // Set a fixed session ID just for the sake of our example.
  23. session_id('example_session_id');
  24. session_start();
  25. if (isset($_SESSION['foo'])) {
  26. echo "Session has `foo` set to {$_SESSION['foo']}\n";
  27. } else {
  28. $_SESSION['foo'] = $value = mt_rand();
  29. echo "Empty session, `foo` has been set with $value\n";
  30. }