I've fixed my login page to create a user entry with an insert statement and the logout button on the next page delete the user but the issue is when I click log-in the user becomes registers but my page does not redirect to the next page automatically, I have to refresh the page then it leads to the next page because a user is seen as logged in. This is my code:
<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>
Also when I log out the user is deleted correctly but then when I load the page from netbeans it takes me to index_1
because it seems the cookie was not deleted? Any help would be great! Again my question is how to redirect it correctly to index_1
and how to properly delete the cookie when I log out.