dsb238100
dsb238100
2014-07-01 12:54
浏览 43
已采纳

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条回答 默认 最新

  • douliao8760
    douliao8760 2014-07-01 13:01
    已采纳

    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

    点赞 评论

相关推荐