1
votes

I've got the following code to show when a user is logged in and when they're not.

<?php
global $user;
if ($user->uid > 0) {
  echo "You are logged in as: " . $user->name . "<br>";
} else {
  echo "You are not logged in!<br>";
}
?>

I want to add a logout link (when logged in) & and a login link (when not logged in). Would I just use html < a > links? If so, how would I incorporate them?

3

3 Answers

1
votes

In most cases you would just use a regular menu and add the two items.

The visibility of the items is controlled by drupals menu-system, so you won't see the login-link if you're already logged in and you won't see the logout-link if you're not logged in.

If you want to output the links programmatically I would recommend using the "l" function

l($text, $path, array $options = array())

To check if a user is logged in you can simply use the user_is_logged_in function provided by the users module.

So your code would become

<?php
if( user_is_logged_in() ) {
  print l('logout', 'user/logout');
}
else {
  print l('login', 'user/login');
}
0
votes

Depends on where you want to show the links. If it is on the same page/piece of code, just go ahead and echo them:

<?php
global $user;
if ($user->uid > 0) {
   echo "You are logged in as: " . $user->name . "<br>";
   echo "<a href=\"logout.php\">Logout</a>";
} else {
   echo "You are not logged in!<br>";
   echo "<a href=\"login.php\">Login</a>";
}
?>
0
votes

You can simply use the url function of Drupal core as below

<?php
global $user;
if ($user->uid > 0) {
  echo '<a href="'.url('user/logout').'">Logout </a>';
} else {
  echo '<a href="'.url('user/login').'">Logout </a>';
}
?>

Hope this will help you :)