Cookies PHP,维护会话

I need some help mantaining user sessions in case my webserver fails. I have a HAProxy configured that spreads user requests to my 2 webservers.

Let's say user A logs in on Webserver 1, and if Webserver 1 fails, HAProxy sends the request to the next available Webserver, in this case, Webserver 2.

My problem is that I can't manage to save the user session, when WebServer 1 fails and send it over to WebServer 2. So my friends suggested me to use cookies in PHP. I'm not familiar with cookies in PHP, but apperantly it's similiar to SESSIONS.

Here's my code that logs a user in: login.php

  $conn_error = 'Could not connect.';
  $mysql_db = 'grupo5';
  if(!mysql_connect('localhost', 'vitorpnm', '') || !mysql_select_db($mysql_db)) {
  die($conn_error);
}

$username = $_POST['username'];
$password = $_POST['password'];

$userBusca = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");

if (mysql_num_rows($userBusca) == 1) {
    session_start(); //inicia sessao

      $_SESSION['id'] = $_POST['username'];
      $_SESSION['password'] = $password;

      header("Location:main.php");

} else {
  echo '<a href="javascript:history.go(-1)">Utilizador e/ou senha invalidos! (Clique aqui para voltar a pagina de login)</a>';
}

?>

Verify if user is logged in or not

@session_start();
    if(isset($_SESSION['id'])) {

    } else { //user not logged in
    header("Location:ask_login.php");
    }
?>

1个回答

For cookie you just have to do these changes:

<?php
$conn_error = 'Could not connect.';
$mysql_db = 'grupo5';
if (!mysql_connect('localhost', 'vitorpnm', '') || !mysql_select_db($mysql_db)) {
    die($conn_error);
}

$username = $_POST['username'];
$password = $_POST['password'];

$userBusca = mysql_query("SELECT * FROM users WHERE id='$username' AND password='$password'");

if (mysql_num_rows($userBusca) == 1) {
    session_start(); //inicia sessao

    setcookie('id', $_POST['username']); //$_SESSION['id'] = $_POST['username'];
    setcookie('password', $_POST['password']); //$_SESSION['password'] = $password;

    header("Location:main.php");
} else {
    echo '<a href="javascript:history.go(-1)">Utilizador e/ou senha invalidos! (Clique aqui para voltar a pagina de login)</a>';
}
?>

Check if user is logged in:

<?php

if (isset($_COOKIE['id'])) {

} else { //user not logged in
    header("Location:ask_login.php");
}
?>

But remember: Cookies are saved local on the client pc. So the user can watch the cookie values. It would be the best you encrypt the cookie data so the user can't see the values in plain text.

What you can do with cookies aswell you can read here: PHP-Manual for set_cookie

dtxw20878
dtxw20878 谢谢你,工作就像一个魅力。
6 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐