我无法在localhost中的php文件中进行会话。即使我创建了一个会话,我也被重定向

时间:2014-03-30 07:08:45

标签: php session cookies

这是我的login.html代码

<html>
<head>
<title>User Logon</title>
</head>
<body>
  <h2>User Login </h2>
  <form name="login" method="post" action="login.php">
   Username: <input type="text" name="username"><br>
   Password: <input type="password" name="password"><br>
   Remember Me: <input type="checkbox" name="rememberme" value="1"><br>
   <input type="submit" name="submit" value="Login!">
  </form>
</body>
</html>

这是login.php

<?php
/* These are our valid username and passwords */
$user = 'jonny4';
$pass = 'delafoo';

if (isset($_POST['username']) && isset($_POST['password']) ){

    if (($_POST['username'] == $user) && ($_POST['password'] == $pass)) {    

        if (isset($_POST['rememberme'])) {
            /* Set cookie to last 1 year */
            setcookie('username', $_POST['username'], time()+60*60*24*365);
            setcookie('password', md5($_POST['password']), time()+60*60*24*365);

        } else {
            /* Cookie expires in an hour */
            setcookie('username', $_POST['username'],time()+60*60);
            setcookie('password', md5($_POST['password']),time()+60*60););
        }
        header('Location: index.php');

    } else {
        echo 'Username/Password Invalid';
    }

} else {
    echo 'You must supply a username and password.';
}
?>

这是index.php

<?php
/* These are our valid username and passwords */
$user = 'jonny4';
$pass = 'delafoo';

if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {

    if (($_POST['username'] != $user) || ($_POST['password'] != md5($pass))) {    
        header('Location: login.html');
    } else {
        echo 'Welcome back ' . $_COOKIE['username'];
    }

} else {
    header('Location: login.html');
}
?>

现在,索引文件检查cookie,如果不可用,则重定向到login.html

login.html获取值,传递给login.php,后者创建cookie。

但不管我做了多少次,输出都是一样的,我无法查看索引文件,因为没有cookie ..有什么帮助吗?

2 个答案:

答案 0 :(得分:1)

您需要更改此部分:

if (($_POST['username'] != $user) || ($_POST['password'] != md5($pass))) {    
    header('Location: login.html');
} else {
    echo 'Welcome back ' . $_COOKIE['username'];
}

要:

if (($_COOKIE['username'] != $user) || ($_COOKIE['password'] != md5($pass))) {    
    header('Location: login.html');
} else {
    echo 'Welcome back ' . $_COOKIE['username'];
}

请注意,$_POST已更改为$_COOKIE

答案 1 :(得分:0)

检查index.php文件。它有错误

<?php
/* These are our valid username and passwords */
$user = 'user';
$pass = 'user';

if (isset($_COOKIE['username']) && isset($_COOKIE['password'])) {
//var_dump($_COOKIE['username']); exit;
    if (($_COOKIE['username'] != $user) || ($_COOKIE['password'] != md5($pass))) {    
        header('Location: login.html');
    } else {
        echo 'Welcome back ' . $_COOKIE['username'];
    }

} else {
    header('Location: login.html');
}
?>