Hello,

I am learning PHP. Now, I am creating login page.

This is my index.php codes

  <?php
    require "../config.php";
    session_start();

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

    if(!$username && !$password){   
        header('Location: login.php');
    } else {
        echo $hello.$username;
    }

    ?>

And this is my login.php

<?php
require "../config.php";
session_start();

function loginForm(){

        echo "<form method='post' action='?action=dologin'>"
                ."<div id='login-box'>"
                ."<span class='label'>Username</span>"
                ."<input type='text' name='username'><br>"
                ."<span class='label'>Password</span>"
                ."<input type='text' name='password'><br>"
                ."<input type='submit' value='Submit'>"
                ."</div>"
                ."</form>"
        ;

}

function login(){
    $username = mysql_real_escape_string($_POST['username']);
    $password = mysql_real_escape_string($_POST['password']);


    $query = mysql_query("SELECT * FROM user WHERE username='$username' AND password='$password'");
    $row = mysql_fetch_array($query);
    $id = $row['id'];
    $username = $row['username'];


    session_register("id", $id);
    session_register("username", $username);
    session_register("password", $password);

switch($action){
    case 'dologin';
        login();    
    break;

    default:
        loginForm();
}

?>

When user submit the loginForm, it should be go to login() but it just go back to the form. I think the problem is in the switch case. How to fix it ?

Thank you

Dani AI

Generated

A short, practical follow-up to what happened in this thread: the original symptom (the form always reappearing) was caused by relying on an undefined $action variable — as pointed out — so the switch always fell to the form. After that was fixed confirmed the username could be read from the session. The notes below expand on that fix with safer, modern practices and a minimal example to apply immediately.

Move off the old mysql_* workflow and use PDO or MySQLi with prepared statements; this both modernizes the codebase (ext/mysql was removed in PHP 7) and removes a large class of injection bugs. Use parameter binding rather than building SQL strings by hand. (php.net)

Do not store or compare plaintext passwords. Store a one-way hash (password_hash) when creating accounts and verify using password_verify at login; keep only a small identity in the session (user id, role, maybe username) — never the raw password. Regenerate the session id on successful login to reduce session fixation risk, and use secure cookie attributes (Secure, HttpOnly, SameSite) and short timeouts for authenticated sessions. (php.net)

Minimal login-processing pattern (example — adapt DSN/column names to the project):

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // $pdo comes from a central config (DSN, user, pass)
    $stmt = $pdo->prepare('SELECT id, username, password_hash FROM users WHERE username = ?');
    $stmt->execute([$_POST['username']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($user && password_verify($_POST['password'], $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['user_id']   = $user['id'];
        $_SESSION['username']  = $user['username'];
        header('Location: /index.php');
        exit;
    }

    $error = 'Invalid credentials';
}

Quick checklist / troubleshooting points

  • session_start() must run before reading/writing $_SESSION or sending session cookies.
  • Use $_SERVER['REQUEST_METHOD']=='POST' or filter_input() to detect form submissions instead of depending on an unset $action.
  • Use HTML type="password" for password fields and POST for the form.
  • During development enable error_reporting and log DB/exception errors (never echo raw DB errors in production).

These steps address both the immediate control-flow bug and the security gaps in the original code.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589

No need for this is there?

$password = $_SESSION['password'];

These are outdated:

 session_register("id", $id);
 session_register("username", $username);
 session_register("password", $password);

Use...

 $_SESSION["id"] = $id;
 $_SESSION["username"] = $username;

The loginForm function seems to just output HTML - so why not provide an include file

function loginForm(){
      include 'forms/loginform.html';
}

or ...

<?php
function loginForm(){
?>
    <form method='post' action='?action=dologin'>
        <div id='login-box'>
            <span class='label'>Username</span>
            <input type='text' name='username'><br>
            <span class='label'>Password</span>
            <input type='text' name='password'><br>
            <input type='submit' value='Submit'>
        </div>
    </form>
<?php
}
?>

Anyway...

switch($action){
    case 'dologin';
        login();    
    break;
    default:
        loginForm();
}

$action is not declared anywhere. You are depending on $_GET['action'] to set it, but I can't see it - so in that case you will always run loginForm().

Thank you for your help.

The swith case problem is fixed.

Now, I am looking for 'how to get the username from session ?'.

updated:

Sorry, it was fixed. I have got the solution.

Member Avatar for Member #120589

OK, mark as solved?

good work

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.