Hi

I created a login page and register a session with username, however, how can I set the loginok.php page must be login successfully and be able to view? Currently, I can view the loginok.php without login. How should I set the loginok.php code to prevent it?

<?php
session_start();
session_destroy();
$Login=$_POST['login'];
if($Login){ 
$username=$_POST['username'];
$password=$_POST['password'];
// Connect database. 
$conn = mysql_connect ($dbhost, $dbuser, $dbpass);
mysql_select_db ($dbname, $conn);
// Check matching of username and password.
$result=mysql_query("select username, password from account where username='$username' and password='$password'");
if(mysql_num_rows($result)!='0')
	{ // If match.
      session_register("username"); 
      header("location: loginok.php");
      exit;
}else{ // If not match.
header("location: loginfail.php");
      exit;
}
}
?>

    calling session_register("username") is probably not doing what you think it is doing. Try reading up on [man]session_register[/man] in the documentation.

    instead of that, try:
    1) get rid of the session_destory() line...i don't think you need that
    2) instead of doing the session_register line, try storing a value in $SESSION

    $_SESSION['logged_in'] = 1;
    $_SESSION['username'] = $username;
    

    3) Put this code in loginok.php:

    session_start();
    if ($_SESSION['logged_in'] !== 1) {
        header('location: login.php');
        exit();
    }
    

      Hi

      1. May I ask do I need to define logged_in variable in php? Where is that variable come from?

      2. loginok.php is ok, but how can I remove the session when the user close the browser or click a logout button?

      After I logged in and turned to the loginok.php, I closed the browser and reopen loginok.php, it can be shown.

      thanks for your help

        Write a Reply...