In PHP, Simple Session Example Of Login And Logout

<?php

session_start();

if(isset($_SESSION['username']) && isset($_POST['action']) && 'logout' === $_POST['action']){
  unset($_SESSION['username']);
}

if(isset($_POST['username']) && isset($_POST['action']) && 'login' === $_POST['action']){
  $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
  $usernmae = trim($username);
  if($username){
    $_SESSION['username'] = $username;
  } else {
    echo '<p>Error: Invalid login attempt</p>';
  }
}

if(isset($_SESSION['username'])){
  echo '<p>Hello <b>', ($_SESSION['username']), 
    '</b> you are logged in</p>',
    '<form method="post">',
       '<input type="submit" value="Logout"/>',
       '<input type="hidden" value="logout" name="action"/>',
    '</form>';
} else {
  echo '<form method="post">',
	  'Username: <input type="text" name="username"/>',
	  '<input type="submit" value="Submit"/>',
	  '<input type="hidden" value="login" name="action"/>',
    '</form>';
}
?>
Download

Comments

Popular posts from this blog