Good all the time of day, gentlemen.

Long ago, I made session authorization on my site. But looking at the site from the Internet, I see that I did not do everything to the end. Log in to the site, immediately go to another browser and log in from it. Next, restart the first browser and: you are not logged in or log in plz.

The meaning is clear and correct, when authorizing on another computer / in another browser - authorization in the first one should “fly”. Can anyone give an example of such an authorization by session (there are examples on the internet - I do not argue), but as described above when authorizing on another computer / in another browser - authorization on the first one “flew”, or first there was a transition that “under your login / pass "already someone is sitting, and then go to the login page.

I'm afraid to make a mistake with the code, you understand, authorization is a serious matter. And the FULL code, or the correct example from an Internet would be very useful. Help solve this problem. Thanks in advance.

up. Grateful for the examples below, but there was a problem:

Written above applied. How well - I do not know. Now, if someone has logged in, then on another computer / browser under this login / password it is impossible to log in anymore. What I did not want. I wanted an authorization in which only the last person logged in could work. Tell me where it was wrong or the code of the simplest authorization, where those who logged in NOT the last one, under one login / pass, are thrown away.

  • It seems to me that this question is purely logical thinking that you, @mixalef, do not possess, do you? - AseN

3 answers 3

@Kite , I wanted to say this:

session_start(); mysql_connect(DB_HOST,DB_USER,DB_USER_PASSWORD) or die(mysql_error()); mysql_select_db(BD_NAME) or die(mysql_error()); mysql_query('SET NAMES '.DB_CHARSET.''); ##Определяем константы для авторизаций define('USERS_TABLE','online_order_users'); define('SID',session_id()); ##Определяем функции //Функция выхода. //Пользователь считается авторизированым, если в сессии присутствует uid //см. "Действия - если пользователь авторизирован". function logout() { unset($_SESSION['uid']); //Удаляем из сессии ID пользователя die(header('Location: '.SITE_URL)); } //Функция входа. //Все выбраные поля записываются в сессию. //Таким образом, при каждом просмотре страницы не надо выбирать их заново. //Для обновления информации из БД можно пользоваться этой же функцией - имя и пароль //хранятся в сессиях function login($username,$password) { $result = mysql_query("SELECT * FROM `".USERS_TABLE."` WHERE `username`='$username' AND `password`='$password';") or die(mysql_error()); $USER = mysql_fetch_array($result,1); //Генерирует удобный массив из результата запроса if(!empty($USER)) { //Если массив не пустой (это значит, что пара имя/пароль верная) $_SESSION = array_merge($_SESSION,$USER); //Добавляем массив с пользователем к массиву сессии mysql_query("UPDATE `".USERS_TABLE."` SET `sid`='".SID."',last=now() WHERE `uid`='".$USER['uid']."';") or die(mysql_error()); return true; } else { return false; } } //Функция проверки залогинности пользователя. //При входе, ID сессии записывается в БД. //Если ID текущей сессии и SID из БД не совпадают, производится logout. //Благородя этому нельзя одновременно работать под одним ником с разных браузеров. function check_user($uid) { $result = mysql_query("SELECT `sid` FROM `".USERS_TABLE."` WHERE `uid`='$uid';") or die(mysql_error()); $sid = mysql_result($result,0); return $sid==SID ? true : false; } ##Действия - если пользователь авторизирован if(isset($_SESSION['uid'])) { //Если была произведена авторизация, то в сессии есть uid //Константу удобно проверять в любом месте скрипта define('USER_LOGGED',true); //Создаём удобные переменные //Все поля таблицы пользователей записываются в сесси (см. стр. 35-37) //Таким образом, после добавления нового поля в таблицу надо дописть лишь одну строку $UserName = $_SESSION['username']; $UserPass = $_SESSION['password']; $UserID = $_SESSION['uid']; } else { define('USER_LOGGED',false); } ##Действия при попытке входа if (isset($_POST['login'])) { if(get_magic_quotes_gpc()) { //Если слеши автоматически добавляются $_POST['user']=stripslashes($_POST['user']); $_POST['pass']=stripslashes($_POST['pass']); } $user = mysql_real_escape_string($_POST['user']); $pass = mysql_real_escape_string($_POST['pass']); if(login($user,$pass)) { die(header("location: ".$_SERVER['REQUEST_URI'])); //die('Вы успешно авторизировались!'); } else { header('Refresh: 3;'); die(' <html> <head> <title>Password or Login incorrect!</title> </head> <body style="background-color:gray;"> <h2 style="text-align:center;color:red;margin-top:200px;">PASSWORD or LOGIN FAILED!</h2> <h3 style="text-align:center;color:yellow;margin-top:20px;">Redirecting...</h3> </body> </html>'); } } ##Действия при попытке выхода if(isset($_GET['logout'])) { logout(); } ?> 
  • I voiced the idea, and in terms of reading / writing sessions in the database, I rather meant setting [standard PHP handlers] [1] to work with them. And the implementation itself is at the discretion of the topstarter. [1]: php.net/manual/ru/session.customhandler.php - KiTE
  • Oh, I do not even know how to say it. written above applied. how well I do not know. Now, if someone has logged in, then on another computer / browser under this login / password it will not be possible to log in. What I did not want. I wanted an authorization in which only the last person logged in could work. Tell me where it was wrong or the code, the simplest authorization, where those who logged in NOT the last one, under one login / pass, are thrown away. - sergey
  • one
    That's right, it should be. Login -> record user in session -> delete other sessions of this user. As a result, there is one session left from the place of the last login. If the user relogs from the new point, the previous session will be deleted. - KiTE
  • yes, this is exactly how the code works - Vfvtnjd

Write the session in the database table. After login, do check if there are other sessions from this user in this table. If so, delete them.

    I suppose you need to write to the database authorized users. After that, upon authorization, check whether a user exists in the table with authorized users, i.e. it turns out like this: When logging in add something like this:

     $username = $_POST['username']; mysql_query('INSERT INTO таблица_с_авторизованными(user) VALUES("$username")'); 

    At the beginning of authorization, do a check:

     $username = $_POST['username']; $res = mysql_query('SELECT user FROM таблица_с_авторизованными WHERE user="$username"'); $nr = mysql_num_rows($res); if($nr>0) echo 'Вы уже авторизованы на другом браузере/компьютере.'; else{ //Авторизация } 

    On exit:

     $username = $_SESSION['username']; unset($_SESSION['username']); //... mysql_query('DELETE FROM таблица_с_авторизованными WHERE user="$username"');