$_SESSION is a way of saving a static variable that can read over pages during a single log in session. Session stores values in an array format. These values are saved on the server side and can be started and destroyed. They are really useful for security checking an account in a log in based project.
start session - this needs to be included on each page where you wish to access a $_SESSION variable
session_start()
To access or set a session variable in the array
$_SESSION['var_name']
$_SESSION["logIn"] = true;
$_SESSION['username'] = $username;
Log out script. You need to destroy the session (session_destroy()) and unset the session variable to clear the contents from the server.
<?php
session_start();
// remove all session variables
session_unset();
// destroy the session
session_destroy();
header('location:login.php');
?>
login.php
<?php
include('connect.php');
$error="";
if(isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "select * from logins where username like '".$username."'";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
if($row['password']==$password){
session_start();
$_SESSION["logIn"] = true;
$_SESSION['username'] = $username;
header('location:example.php');
}else{
$error="Incorrect password";
}
}
}
else{
$error="Username does not exist";
}
}else{
$error="Please enter username and password";
}
?>
<html>
<body>
<h1>Log In Form</h1>
<form method="post" action="login.php">
<label for="username">Username:</label>
<input type="text" name="username" required>
<label for ="password">Password:</label>
<input type="password" name="password" required></br>
<p><?php echo $error ?></p>
<input type="submit">
</form>
</body>
</html>
logout.php
<?php
session_start();
// remove all session variables
session_unset();
// destroy the session
session_destroy();
header('location:login.php');
?>
example.php
<?php
//this code will need to go at the top of each secure page
include('connect.php');
echo('<h1>Example page</h1>');
echo('<a href ="logout.php">Log Out</a>');
//check login
session_start();
if($_SESSION['logIn']!=true){
header("location:login.php");
}else{
echo('Hello '. $_SESSION['username']);
}
?>