session_handler.php 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. /*
  3. * This file is part of the Predis package.
  4. *
  5. * (c) Daniele Alessandri <suppakilla@gmail.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. require __DIR__.'/shared.php';
  11. // This example demonstrates how to use Predis to save PHP sessions on Redis.
  12. //
  13. // The value of `session.gc_maxlifetime` in `php.ini` will be used by default as
  14. // the TTL for keys holding session data but this value can be overridden when
  15. // creating the session handler instance using the `gc_maxlifetime` option.
  16. //
  17. // NOTE: this class requires PHP >= 5.4 but can be used on PHP 5.3 if a polyfill
  18. // for SessionHandlerInterface is provided either by you or an external package
  19. // like `symfony/http-foundation`.
  20. //
  21. // See http://www.php.net/class.sessionhandlerinterface.php for more details.
  22. //
  23. if (!interface_exists('SessionHandlerInterface')) {
  24. die('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 '.
  25. "or a polyfill for SessionHandlerInterface provided by an external package.\n");
  26. }
  27. // Instantiate a new client just like you would normally do. Using a prefix for
  28. // keys will effectively prefix all session keys with the specified string.
  29. $client = new Predis\Client($single_server, array('prefix' => 'sessions:'));
  30. // Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
  31. $handler = new Predis\Session\Handler($client, array('gc_maxlifetime' => 5));
  32. // Register the session handler.
  33. $handler->register();
  34. // We just set a fixed session ID only for the sake of our example.
  35. session_id('example_session_id');
  36. session_start();
  37. if (isset($_SESSION['foo'])) {
  38. echo "Session has `foo` set to {$_SESSION['foo']}", PHP_EOL;
  39. } else {
  40. $_SESSION['foo'] = $value = mt_rand();
  41. echo "Empty session, `foo` has been set with $value", PHP_EOL;
  42. }