Главная страница  /  Занятия  /  #16  /  Создание, использование и удаление сессий в PHP

Создание, использование и удаление сессий в PHP

Задание:

Рассказать о создании, использовании и удалении сессий в PHP.

phtml-документы:

Файл index.phtml:

   <?
    session_start();
?> <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Первая страница</title> <link rel="stylesheet" href="styles.css"> <script src="scripts.js"></script> </head> <body> <h1>Первая страница</h1> <?
    if(sizeof($_SESSION)) echo '<pre>Количество сессионных переменных: '.sizeof($_SESSION).'<br><br>'.print_r($_SESSION, true).'</pre>';
    else print '<pre>Сессия пуста</pre>';
?> <button>Добавить переменную сессии</button> <button>Удалить переменную сессии</button> <button>Удалить сессию</button> <button>&nbsp;Вторая страница &nbsp;&rarr;</button> </body> </html>

Файл second.phtml:

   <?
    session_start();
?> <!DOCTYPE html> <html lang="ru"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Вторая страница</title> <link rel="stylesheet" href="styles.css"> <script src="scripts.js"></script> </head> <body> <h1>Вторая страница</h1> <?
    if(sizeof($_SESSION)) echo '<pre>Количество сессионных переменных: '.sizeof($_SESSION).'<br><br>'.print_r($_SESSION, true).'</pre>';
    else print '<pre>Сессия пуста</pre>';
?> <button>Добавить переменную сессии</button> <button>Удалить переменную сессии</button> <button>Удалить сессию</button> <button>&larr;&nbsp; Первая страница&nbsp;</button> </body> </html>

CSS-разметка (styles.css):

   body					{ font-family: Arial, Tahoma, Verdana; font-size: 16px; }
   h1					{ background-color: #f0f0f0; padding: 16px; margin: 0px; }
   pre					{ border: 1px solid #f0f0f0; padding: 16px; margin: 0; }
   button				{ height: 36px; font-size: 16px; background-color: #f0f0f0; border: 1px solid #d0d0d0; margin-top: 18px; outline: none; cursor: pointer; }
   button:nth-of-type(1)		{ width: 280px; margin-right: 10px; }
   button:nth-of-type(2)		{ width: 270px; margin-right: 10px; }
   button:nth-of-type(3)		{ width: 180px; margin-right: 10px; }
   button:nth-of-type(4)		{ width: 200px; }

JS-скрипты (scripts.js):

   var sessionVariableName = '';
   var sessionVariableValue = '';
   var xhr = new XMLHttpRequest();
   
   window.onload = function()
   {
    document.getElementsByTagName('button')[0].onclick = function()
    {
     sessionVariableName = prompt('Введите имя переменной');
     sessionVariableValue = prompt('Введите значение переменной');
     xhr.open('GET', 'managesession.php?action=addsessionvariable&sessionvariablename='+sessionVariableName+'&sessionvariablevalue='+sessionVariableValue, true);
xhr.responseType = 'text'; xhr.send(); }; document.getElementsByTagName('button')[1].onclick = function() { sessionVariableName = prompt('Введите имя переменной');
     xhr.open('GET', 'managesession.php?action=deletesessionvariable&sessionvariablename='+sessionVariableName, true);
xhr.responseType = 'text'; xhr.send(); }; document.getElementsByTagName('button')[2].onclick = function() {
     xhr.open('GET', 'managesession.php?action=destroysession', true);
xhr.responseType = 'text'; xhr.send(); }; document.getElementsByTagName('button')[3].onclick = function() { switch(this.innerHTML) { case '←&nbsp; Первая страница&nbsp;': document.location.href = window.location.protocol+'//'+window.location.host+window.location.pathname.replace(/[^\/]+$/, ''); break; case '&nbsp;Вторая страница &nbsp;→': document.location.href = window.location.protocol+'//'+window.location.host+window.location.pathname+'second.phtml'; break; } }; }; xhr.onload = function() { document.getElementsByTagName('pre')[0].innerHTML = xhr.response; };

PHP-скрипты (managesession.php):

   <?
    session_start();
    header('Content-Type: text/html; charset=utf-8');
   
    switch($_GET['action'])
    {
     case 'destroysession':
      $_SESSION = array();
      if(ini_get('session.use_cookies'))
      {
       $cookieParams = session_get_cookie_params();
       setcookie(session_name(), '', time() - 42000, $cookieParams['path'], $cookieParams['domain'], $cookieParams['secure'], $cookieParams['httponly']);
      }
      session_destroy();
break; case 'addsessionvariable':
      if(preg_match("/^[a-z\_][a-z\_\d]*$/i", $_GET['sessionvariablename'])) $_SESSION[$_GET['sessionvariablename']] = $_GET['sessionvariablevalue'];
break; case 'deletesessionvariable':
      if(preg_match("/^[a-z\_][a-z\_\d]*$/i", $_GET['sessionvariablename'])) unset($_SESSION[$_GET['sessionvariablename']]);
break; } if(sizeof($_SESSION)) echo 'Количество сессионных переменных: '.sizeof($_SESSION).'<br><br>'.print_r($_SESSION, true); else print 'Сессия пуста'; return; ?>

Результат:

Результат выполнения задания можно посмотреть здесь.