1

What is the best way to make a logout link? I want to destroy all my sessions and do a redirect back to the login page but I'm not sure the best way to do this. Right now I have the link leading to a admin/logout.php but I feel like it would be a bad thing to show the user my folder structure. Here's my code it's pretty straight forward:

session_start();
    session_destroy();
        echo "<script type=\"text/javascript\">window.location.href='../login.php';</script>";

So would it be best to do something in javascript or ajax?

Howdy_McGee
  • 10,422
  • 29
  • 111
  • 186
  • 2
    Why redirect via JS when you can just do `header("Location: login.php")`? – Marc B Jan 21 '12 at 06:24
  • Check this out: http://stackoverflow.com/questions/2241769/php-how-to-destroy-the-session-cookie-correctly – Josh Jan 21 '12 at 06:26
  • @MarcB I asked a question awhile ago that said javascript redirects were the best choice and I was going to link it, but then it got a bunch of comments on how bad it was so I probablyyyy should go back and change that xD – Howdy_McGee Jan 21 '12 at 06:30

2 Answers2

3

If you're worried about exposing directory structure, then don't use directories. Simply have ALL of your pages check for a logout query parameter:

<?php
if (isset($_GET['logout'])) {
   session_start();
   session_destroy();
   header("Location: login.php");
   exit();
}

That way you can logout from ANY page, your 'admin' folder never gets exposed, and doing the header() redirect means there's no chance for a user to interrupt any of the other redirect methods you could use (meta tag, javascript, etc...). There simply will be NOTHING on the page for the user to see, because you didn't output anything.

Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Yeah the javascript redirect was the problem. Some reason it exposed my directory structure but when i changed to header() - that was fixed. Also I like the `$_GET[]` idea instead of making an entirely new file just to logout. – Howdy_McGee Jan 21 '12 at 06:39
0

logout.php :

<?php
session_start();
session_destroy();
?>
<html>
<head>
<meta HTTP-EQUIV="REFRESH" content="0; url=login.php">
</head>
</html>

this needs to be a separate .php page. Just link to it, and they will not see this, instead they will see the contents of index.php but with no session data stored :)

This is probably the best and easiest way of going about this. All in simple PHP, with an HTML redirect.

Pablo Canseco
  • 554
  • 1
  • 10
  • 24
  • See that's what I thought... My `admin/logout.php` looked like the code linked in my question (inside php tags) with no HTML. But the URL still went to /admin/logout.php then. I think my problem ended up being that javascript redirect since it does not do this when I use `header()` instead – Howdy_McGee Jan 21 '12 at 06:37