r/PHPhelp • • Sep 11 '25

login check not working

I am try to stop users accessing a page without being logged in. Any help appreciated

code on html page

<?php session_start(); // Check if user is logged in if (!isset($_SESSION\['user_id'\])) { // Redirect to login page header("Location: login.html"); exit(); } ?>

The page will load even if I use a device I have never logged onto the page with.

This is the code used when I logout of the page

<?php ob_start(); session_start(); // Clear session data $_SESSION = \[\]; session_unset(); session_destroy(); // Remove session cookie i dont use cookies anyway if (ini_get("session.use_cookies")) { $params = session_get_cookie_params(); setcookie(session_name(), '', time() - 42000, $params\["path"\], $params\["domain"\], $params\["secure"\], $params\["httponly"\] ); } // Prevent caching i dont think this is the issue header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0"); header("Pragma: no-cache"); ob_end_clean(); echo "You’ve been logged out successfully."; echo '<meta http-equiv="refresh" content="5;url=index.html">'; ?>

2 Upvotes

6 comments sorted by

3

u/Big-Dragonfly-3700 Sep 12 '25

code on html page

What is the file extension of the 'protected' page?

What do you get when you do a 'view source' in your browser of the protected page?

1

u/bigfellani5 Sep 12 '25 edited Sep 12 '25

Thankyou for the reply

It is a html page (dashboard.html

when I view source I can see the source code of the page

The HTML code starts ofter this code is placed on the top of the page

<?php session\\_start(); // Check if user is logged in if (!isset($\\_SESSION\\\['user\\_id'\\\])) { // Redirect to login page header("Location: login.html"); exit(); } ?>

2

u/MateusAzevedo Sep 12 '25

It is a html page (dashboard.html

That's the issue then. Your webserver is serving that page directly, without even calling PHP to execute the code on it.

2

u/bigfellani5 Sep 12 '25 edited Sep 12 '25

I am a ameture coder haha

so if I change the file name extension to php that will then fix my problem

1

u/No_Astronomer9508 Sep 12 '25

Better Solution: Check if Session ist valid -> Include your Dashboard -> Else Error Message and/or redirect to Login page.

0

u/[deleted] Sep 12 '25

[deleted] — view deleted comment

1

u/MateusAzevedo Sep 12 '25

What do you mean? It looks fine to me.