I need to Hide ‘Section1’ div and Log out button, if user not logged in. in here, checking if user logged in. if it’s true, then displaying the user’s name in the menu section. if it’s not, it will showing ‘login or register’ buttons.
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Home</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
<script src="https://kit.fontawesome.com/62c1d859ff.js" crossorigin="anonymous"></script>
</head>
<body>
<!-- Header Section -->
<div class="nav">
<ul>
<li><a href="">Home</a></li>
<li><a href="">Orders</a></li>
<li><a href="">Contact</a></li>
</ul>
<div class="icon" id="icon">
</div>
</div>
<div class="menu" id="menu">
<div class="username">
<div class="icon"></div>
<h3 class="name">
<?php echo isset($_SESSION['user_name']) ?
$_SESSION['user_name'] :
'<span class="login_register"><a href="signin.php">Login</a> or <a href="register.php">Register</a><span/>';
?>
</h3>
</div>
<div class="section1">
<li><a href="profile.php"><i class="fa-solid fa-user"></i>Your Profile</a></li>
<li><a href="settings.php"><i class="fa-solid fa-gear"></i>Settings</a></li>
<li><a href=""><i class="fa-solid fa-circle-info"></i>Help</a></li>
<li><a href=""><i class="fa-regular fa-message"></i>Send Feedback</a></li>
</div>
<form action="logout.php" method="POST">
<button type="submit" class="logout"><i class="fa-solid fa-arrow-right-from-bracket"></i>Logout</button>
</form>
</div>
</body>
</html>
I tried different methods, but i didn’ get what i expected..
2
Answers
In my experience, I block users before entering the page if they are not logged in,
and in login page,
With this solution, I don’t have to modify the HTML content, but blocking them before entering the page. So they need to login first to see their profile or their information.
To hide these sections, you can simply test the session value, in a similar way to how your code already decides whether to show the username, or show the login button instead:
N.B. It’s unclear if you realise this or not, but simply hiding these links will not prevent access to the pages that they link to. You will need to ensure that each of these pages has code at the start of it to check the user’s login status before displaying the content, and redirect them back to the login page if there is no valid username in the Session. This will prevent anyone from going to those pages directly via the URL, without using the links in your menu.