Issue displaying error

Hi. This is an issue I know what I need to do, just cant think of a way to do it. If a user is not logged in and tries to access a members page, an error should be displayed to them.

My issue at the moment is this. I have a div which displays the result of a function. The function is

function displayStatus(){
   global $log_in; 
   include "MPage.php";
  
   if($log_in){ //if user logged in
       showMembersPage();
   }else{ //else not logged in
	   showLoginForm(); 
	   processLoginForm(); 
   }
}

So, if the user is logged in, it will display showMembersPage within the div, if not, it will display the login form. The showMembersPage function is

function showMembersPage(){
    echo "Logged In";
}

If the user tries entering the direct url to the members page, nothing at all displays, which is understandable. However, I need to put somewhere within this members page that if the user is not logged in, display an error. I have tried the usual if statement, but this doesnt work. I have a feeling this is because this page is only called up if the member is logged in, and if they access it directly, it will never be invoked.

This made me think I need to do it in the first page, but then the else statement is displaying and processing the form. Not sure where I can get the error displayed.

Any advise appreciated.

I think you are making this way more complicated than it needs to be.

when a user logs in, your authentication script (the one that checks the username /password in the db) should set a session variable if the username/password exists in the db.

for example set $_SESSION[‘sessVar’] = ‘someValue’ if the username/password exists.

then on every member page at the very top you can do something like this:

 
<?php
session_start();
 
if(!isset($_SESSION['sessVar']) || empty($_SESSION['sessVar']) || $_SESSION['sessVar'] != 'someValue') {
      die('<p>You are not logged in</p>');
}
 
//add the code for this page below here
 
 
?>

so if a user enters the url of a member’s page directly in their browser without first logging in, they will get the above error message and the script will terminate.

other options include using include() to display the login form in the IF block I posted or simply a link to your login page before terminating the script.

Its a bit difficult in my situation, as all the pages are essentially one page. Therefore, if I do something similar to what you suggest, everytime I try to display the login form, I will get the error as I am not logged in. Will have to try and think of a logical way around this.

Just one more thing. If I have if statements for validation, and after these I have code that executes some action, If I place a die() within the if statements, will this stop the code outside them being executed if the if statement has been invoked?
Sorry if its confusing!

what happened when you tried it?