Search code examples
loggingauthenticationlogin-controllogin-script

Login page to show "welcome user" on index.php


I created login page and everything works, but redirects me to a new page saying i wrote in ECHO, but i want it to show it in index.php with sign in upper right corner "Welcome USERNAME". Like on facebook when you login it says "WELCOME USER"

Here is index.php

<!DOCTYPE html>
<html>

<head>

    <title>NAME</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="css/login.css"/>
    <meta name=viewport content="width=device-width, initial-scale=1">

</head>

<body>
    <div id="login">
        <h1>Welcome to NAME</h1>
        <h2>LOGIN OR REGISTER<br/>TO CONTINUE</h2>
        <form action="login.php" method="POST" class="input">

            <label for="username">Username</label><br/>
            <input type="text" name="username"> <br/>

            <label for="password">Password</label><br/>
            <input type="password" name="password"> <br/>

            <input type="submit" value="Login">         
        </form>
    </div>
</body>

</html>

and here is login.php

<?php
session_start();

    $username = $_POST ['username'];
    $password = $_POST ['password'];

    if ($username&&$password)
    {
        $connect = mysql_connect ("localhost","root","") or die ("Could not connect");
        mysql_select_db ("logintest") or die ("Could not find database");
        $query = mysql_query ("SELECT * FROM users WHERE username='$username'");
        $numrows = mysql_num_rows ($query);

        if ($numrows !=0)
        {

            while ($row = mysql_fetch_assoc($query))

            {
                $dbusername = $row ["username"];
                $dbpassword = $row ["password"];
            }

        if ($username==$dbusername&&$password==$dbpassword)
            {
                echo "Welcome USER";
                $_SESSION ["username"]=$username;

            }
            else
                echo "Incorrect password";
        }
        else
            die ("That user does not exist");
    }
    else
        die("Please enter username and password");

?>

Solution

  • If i'm understanding your question correctly and you are storing the username in a session (as you are), all you need to do is echo $_SESSION["username"] where you want to display it. For instance, in your index.php, just do the following.

    <h1>Welcome to <?php echo $_SESSION ['username']; ?></h1>

    Obviously, remove the space between $_SESSION and the first bracket as it doesn't render in the code block correctly when placed together.

    -- EDIT --

    Remove echo "Welcome USER"; from your login.php

    Modify your index.php:

    <h1>Welcome to <?php echo $_SESSION ['username']; ?></h1>

    To be:

    <h1>Welcome to <?php echo ( !empty($_SESSION ['username']) ) ? $_SESSION ['username'] : 'USER'; ?></h1>