Link to home
Start Free TrialLog in
Avatar of geist62
geist62

asked on

Change a Login link to Logout link using PHP

Haven't been able to get this to work.

I simply want a "Login" link to appear at the top of all of my pages. When user sucessfully logs in this link turns to "Logout". AND displays their "username".

What code do I use (don't want to rely on cookies) and where do I place it? Do I insert code on ALL of my pages?  My pages consist of "Login Registration"; "Login", "Logout".  They all work fine.

Thanks!
Avatar of Kiran Paul VJ
Kiran Paul VJ
Flag of India image

after sucessfull verifcation of usrname and pass, you set a session say username

<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username']!="")
echo("Login");
else
echo("Logout");?>
You must keep track somehow of who is loggedin, so the basic is

if (isset($_COOKIE['USERNAME']) && isset($_COOKIE['PASSWORD']))
    {
     echo "<A HREF=\"logout.php\">Logout</a>
    }
      else
    {
     echo "<A HREF=\"login.php\">Login</a>
     }

Of course you could use session as well.
sorry, interchanged login and logout in above code

and if there is link you can try something like

<?php
session_start();
if(isset($_SESSION['username']) && $_SESSION['username']!="")
{
  echo("<a href='logout.php'>Logout</a><br />");
  echo($_SESSION['username']);// displays username
}
else
{
  echo("Login");
}
?>
Avatar of geist62
geist62

ASKER

Thanks! What I'm trying to understand is where to place your code kiranvj.  If I want the link on every web page do I simply insert it a the top of every page?

Regards!
ASKER CERTIFIED SOLUTION
Avatar of Kiran Paul VJ
Kiran Paul VJ
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@geist62,
you can also do as gamebits mentioned

so ur code will look like

<a href='somepage.php'>Some Link</a>
include('login_logout.php');
<a href='some_other_link.php'>Some other link</a>

//login_logout.php
<?php
if(isset($_SESSION['username']) && $_SESSION['username']!="")
{
  echo("<a href='logout.php'>Logout</a> ");
  echo($_SESSION['username']);// displays username
}
else
{
  echo("<a href='login.php'>Login</a> ");
}
?>

if you include the code as a file you dont need to change it in all files if there is a change in code.