登录页面php重定向和cookie删除

时间:2016-04-19 22:36:48

标签: php mysql cookies login

我已经修复了我的登录页面以创建带有insert语句的用户条目,并且下一页上的注销按钮删除了用户但问题是当我单击登录时用户成为寄存器但我的页面没有重定向自动进入下一页,我必须刷新页面,然后它会进入下一页,因为用户被视为已登录。这是我的代码:

<head>

<?php
if(isset($_POST["Logout"])){
    $saveuser = $_COOKIE["user"];
    $savepass = $_COOKIE["password"];
    $hostname='localhost';
    $username='root';
    $password='';

    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=cs266db_db1",$username,$password);
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
        $sql3 = "DELETE FROM userid
   WHERE user='".$saveuser."' AND password='".$savepass."'";
        if ($dbh->query($sql3)) {
            echo "<script type= 'text/javascript'>alert('Logged out');</script>";
        }
        else{
            echo "<script type= 'text/javascript'>alert('Data not successfull.');</script>";
        }

        $dbh = null;
    }
    catch(PDOException $e) {
        echo $e->getMessage();
    }

    unset($_COOKIE["user"]);
        unset($_COOKIE["password"]);    
}
?>

<?php
if(isset($_POST["submit"])){
    $cookie_user = $_POST["user"];
    $cookie_pass = $_POST["password"];
    setcookie("user", $cookie_user, time() + (86400), "/");
    setcookie("password", $cookie_pass, time() + (86400), "/");

    $hostname='localhost';
    $username='root';
    $password='';
    try {
        $dbh = new PDO("mysql:host=$hostname;dbname=cs266db_db1",$username,$password);

        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
        $sql2 = "INSERT INTO userid
   VALUES ('".$cookie_user."','".$cookie_pass."')";
        if ($dbh->query($sql2)) {
            echo "<script type= 'text/javascript'>alert('Register Complete');</script>";
        }
        else{
            echo "<script type= 'text/javascript'>alert('Data not successfull.'); </script>";
        }
        $dbh = null;
    } 
    catch(PDOException $e) {
        echo $e->getMessage();
    }
}
?>

<?php
if(!isset($_COOKIE["user"])) {
    echo"<form action="."''"."method="."post".">";
    echo"<input type='"."text'"." name='"."user'"." placeholder='"."Enter Username'"." required/><br><br>";
    echo"<input type='"."password'"." name='"."password'"."  placeholder='"."Enter Password'"." required/><br><br>";
    echo"<input type='"."submit'"." name='"."submit'"." value='"."  Register'"."/>";
    echo"</form>";      
}
else {
    header("Location: index_1.php"); /* Redirect browser */
    exit();
}
?>

</head>

此外,当我退出时,用户被正确删除但是当我从netbeans加载页面时,我需要index_1,因为它似乎没有删除cookie?任何帮助都会很棒!我的问题是如何将其正确地重定向到index_1以及如何在我退出时正确删除cookie。

1 个答案:

答案 0 :(得分:0)

在所有关闭和打开PHP标记的情况下,删除空白行。 另外,删除代码顶部的<head>标记以及所有空白行和空格(谢谢@Rasclatt)

长话短说,你应该有一个连续的PHP代码。问题的原因描述为here。您没有看到问题,因为您关闭了错误报告。

而不是:

.
.
.
?>

<?php
.
.
.

应该是:

.
.
.


.
.
.

替代解决方案:使用JavaScript重定向而不是HTTP重定向。