php - Restrict certain elements in a page to logged in users

I'm following this tutorial (https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php) for creating a logging system in PHP and MySQL. To restrict the access to certain pages for logged in users only we use this code:
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
?>
<p>this page is for logged in users only</p>
Anyway, there is a page to view the profile of a user and it should be accessible for logged in or non logged in users, but some aspects of the program should be only available for logged in users, like viewing, say, the bell of the notifications. For now I've been using this way;
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== false){
// user is logged in so display notifications bell
}
?>
This approach works but it doesn't seem very efficient. Any ideas?
Answer
Solution:
Rather than a True/False value I would suggest using something like $_SESSION['username'],
Eg:
<?php
//include any header / common files.
// Start Session
sessoin_start();
//Add function here to check session has not expired
if(!isset($_SESSION['username']))
{
// Do Redirect, then return so no other code is executed
return;
}
// Render Page for logged in user.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: xml parsing error: no root element found
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.