How to add session to this code

I got this code for multi login by using database.
I want to create session which i can limit anyone to access straight to the links without getting logged in.

how i could create session for this login and for other pages to check if the user logged in or not

thanks for the help


<?php
//Start session
session_start();


if(isset($_SESSION['username']) && isset($_SESSION['password']))

{

session_regenrate_id();

}



//$_SESSION['aaa'] = $_POST['username'] . " " . $_POST['password'];
?>
<?PHP

    //Include database connection details
   // require_once('config.php');
    
    //Array to store validation errors
    $errmsg_arr = array();
    
    //Validation error flag
    $errflag = false;
    
    //Connect to mysql server
    $link = mysql_connect('localhost', 'root', '1231');
    if(!$link) {
        die('Failed to connect to server: ' . mysql_error());
    }
    
    //Select database
    $db = mysql_select_db('dbtest');
    if(!$db) {
        die("Unable to select database");
    }
    
    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($str) {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return mysql_real_escape_string($str);
    }
    
    //Sanitize the POST values
    $username = clean($_POST['username']);
    $password = clean($_POST['password']);
    
    //Input Validations
    if($username == '') {
        $errmsg_arr[] = 'Login ID missing';
        $errflag = true;
    }
    if($password == '') {
        $errmsg_arr[] = 'Password missing';
        $errflag = true;
    }
    
    //If there are input validations, redirect back to the login form
    if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        session_write_close();
        header("location: login2.php");
        exit();
    }
    
    //Create query
    $qry="SELECT * FROM login_type WHERE username='".$username."' AND password='".$password."'";
    $result=mysql_query($qry);
    
     $usercategory = "SELECT type FROM login_type WHERE username ='".$username."'";
     $result2 = mysql_query($usercategory);
     $result3 = mysql_fetch_row($result2);
     
    
    if(!$result3){
    $message  = 'Invalid query: ' . mysql_error() . "\
";
    $message .= 'Wrong password or username';// . $usercategory;
    die($message);
    exit();
    }
    
    //Check whether the 1st query was successful or not
    if($result){        
    if(mysql_num_rows($result) == 1){
        //Login successful
            session_regenerate_id();
            $login = mysql_fetch_assoc($result);
            $_SESSION['SESS_username'] = $login['username'];
            $_SESSION['SESS_usercategory'] = $login['usercategory'];
            $_SESSION['SESS_password'] = $login['password'];
            
               session_write_close();
               
               switch($result3[0]){
               
                        case 'admin':
                         header("location: sac_control.php");
                          break;
                          
                        case 'user':      
                          header("location: sac_users.php");
                          break;
                          
                        case 'usermaybank':
                         header("location: sac_maybank.php");
                          break;
						  
						  case 'usereon':
                         header("location: sac_eon.php");
                          break;
                          
                        default: die("all cases never worked");
                    }
                  }else {
                      //Login failed
                     header("location: login-failed.php");
                     exit();
                 }
                }
             
?> 

The login file you can make an global file,other pages include this file or use globla can use it.when the user success log in,you can also set one session flag,write success log in flag!when the user log out your web then change the session flag!


if($result==1){
session_register("usernamec");
session_register("passwordc");
header("location:success.php");
}
else {
echo "There's Error please check your User name or Password";
}

Thanks Alandy for replying… Do you mean that i should register the session the way above.
If it’s different could you plz help me by showing your way that you use session flag!

Thank you again
:slight_smile:

As addition
This is the code including the logout.php file


<?php
session_start();
session_destroy();
header("location:login.php");
?>

But still I’ve problem with the security protracting for the files… i can still access them even if i logged out.:injured:

Hi

On your login page you would check the user supplied Name and password against your database.

If all is well you can simply set a Session varaiable, lets call it $_SESSION[‘loggedin’]

now on each subsequent page you require to be protected you check whether the session variable has been set, if not you redirect the user back to the login page.


if (!isset($_SESSION['loggedin'])){
     // redirect user to login page
}

on logout just destroy the session, and reload the page.

:rolleyes:
Thank you Mandes for explaining that… I get the picture of it…
But when i start to make it i got this error…

Login check


<?php
//Start session
session_start();
if (!isset($_SESSION['loggedin'])){
if ($login[$_POST['username']]['password'] == $_POST['password']){
} else {
echo "Not Right";
}
} else {
echo "Not Right";
} 
?>

The Error :-
Not Right
Warning: session_regenerate_id() [function.session-regenerate-id]: Cannot regenerate session id - headers already sent in C:\xampp\htdocs\login_system\logchek.php on line 87

Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\login_system\logchek.php:7) in C:\xampp\htdocs\login_system\logchek.php on line 98

Each subsequent page Code:


<?php
//Start session
session_start();
if (!isset($_SESSION['loggedin']))
{
# logged in
} 
else
{
# not logged in
header('Location: login2.php');
    exit;
}
?>

Logout page :-


<?php
session_start();

session_destroy();

header("location:login2.php");
?> 

I can feel that my problem is on the part of checking the user supplied Name and password against my database… I dont really know how to code that:x

Thanks always for helping me Mandes

The header() error means your outputting content before the function itself, for example this would cause a header error.

echo 'something';
header('Location: somewhere.php');

Where as the below would work because we have declared the content after the header function there for allowing the script to correctly continue in a semantic manor.

header('Location: somewhere.php');
echo 'something';

Also bear in mind that Session_Start() sends http headers too, so your redirect needs to be either a META redirect, or a javascript redirect.

Another common trap is to check the encoding of the php file, if it is UTF-8 it will contain a BOM (3 bytes that are at the start of the file, normally invisible) this will be classed as output by the server, and you session_start() will raise the headers error.

Thank you Guys for the Help …
I learned a lot really …

Thanks again :slight_smile: