简体   繁体   中英

Redirect to user page after login

Changed my code to the following thanks to the tips. But I'm still not redirected to the user.php. Added the variable $rowcount and give it a value. If the query has a value of a user it have to be redirected to the user.php page.

<?php
    include("inc/header.php");
?>

<?php
    if(isset($_POST["submit"])) {

    $username = trim($_POST["username"]);
    $password = trim($_POST["password"]);

        if($username == "" && $password == "") {
            echo "Please fill in all the details";
            exit;
        }

        if($username == "admin" &$password == "test") {
            $_SESSION["admin"] = true;
            header("location: admin-panel.php");
        } 

        $rowcount = 0;
        $password_secure = md5($password);
        if($username != "" && $password != "") {
            $sql = "SELECT * FROM user WHERE username = '".mysqli_escape_string($connection, $username)."' 
            AND password = '".mysqli_escape_string($connection, $password_secure)."'";
            $query = mysqli_query($connection, $sql);
            $rowcount = mysqli_num_rows($query);
        } else {
            echo "Username of password was not right, please try again.";
        }

        if($rowcount != 0) {
            $row = mysql_fetch_array($connection, $query);
            $_SESSION["username"] = $row["username"];
            $_SESSION["login"] = true;
            header("location: user.php");
            exit;
        }
    }
?>

<?php
    include("inc/footer.php");
?>
// if logged in, redirect towards user account
if($logged_in) {
    header("Location: useraccount.php");
    exit(0);
}

Change $logged_in with your php stracture

Add session_start() at the top of your page. Also change the following code.

session_start();
..
..

if($rowcount == 1) 
{
   while($row = mysqli_fetch_array($query))
   {
        $_SESSION["username"] = $row["username"];
        $_SESSION["login"] = true;
   }
   header("location: user.php");
}

In user.php, first check whether user is logged in or not. For that write a simple function -

function is_loggedin()
{
    if(isset($_SESSION['username']) && isset($_SESSION['login']))
        return TRUE;
    else
        return FALSE;
}

If return FALSE, redirect back to Login page.

Your $rowcount must to be declared at outside of the "if":

$rowcount=0;
if($username != "" && $password != "") {
    $sql = "SELECT * FROM user WHERE username = '".$username."' 
            AND password = '".$password_secure."'";
    $query = mysqli_query($connection, $sql);
    $rowcount = mysqli_num_rows($query);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM