Hello,

I am creating login system with session for secure login and logout. Yet, I don't think it works as it suppose to be.

This is my codes:

admin.php

<?php

// Check if session is not registered, redirect back to main page.
// Put this code in first line of web page.

session_start();

if(!$_SESSION['username'])
    {
    header("location:index.php");
    exit;
    }

?>



<li><a href="logout.php">Logout</a></li>

logout.php

<?php 

session_destroy();

header("location:index.php");

?>

After I logout and goes to index.php I still able to enter admin.php just by typing the url address. I wonder why?

Recommended Answers

All 5 Replies

In logout.php maybe try to use
unset($_SESSION['username']);

<?php 
unset($_SESSION['username']);
session_destroy();
header("location:index.php");
?>

@Banderson:
session_destroy() unsets all session variables bud, so it would be redundant to unset individual variables

@davy_yg:
Always remember what the official definition of session_start() is:

"session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie."

In your logout.php, you can't destroy a session without telling your script which session you want it to destroy. So your existing session needs to be resumed first.

Logout.php:

<?php
    session_start(); // resume current session
    session_destory(); // blow the resumed session to smithereens
    header("Location: index.php"); // redirect
?>

you are forgettig to resume the current session, you want to destroy.

<?php session_start(); //Resumes Session

unset($_SESSION['username']); // Unset Session
header("location:index.php"); // Redirects 

?>

Hello,

I am trying to use the same code for other websites (which I revise the backend template). This is for the logout:

<?php 

session_start(); // resume current session

session_destroy(); // blow the resumed session to smithereens

header("Location: ../index.php"); // redirect


?>

I wonder why I still can re-login to my backend template just by pressing back.

You might be able to re-login, but you shouldn't be able to gain access.

If you can, it means you're also not checking to see if the use is authorised correctly.

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.