It would be better to do an actual redirect to a must be logged in page of some sort than to just echo stuff out. Will be more flexible log term.
You can do redirects in php with header() (make sure you use die() or exit() after the header call), however, you need to do the redirect before you output anything else, or it won't work. I recommend having it in a config file of some sort that you can easily require on every page that can check if the current page should require authentication, and if so, if not authenticated redirect.
Make the 'should require authentication' a function as well as the 'is authenticated' a function and that will simply the logic for you.
Then you can do something like this (just to give you the idea)
if (thisPageRequiresAuthentication && !isAuthenticated) {
header("Location: http://domain.com/mustlogin.php");
die();
}
Header From PHP manual,
https://www.php.net/manual/en/function.header.php
And stackoverflow example using header, the first question seems extensive,
https://stackoverflow.com/questions/768431/how-do-i-make-a-redirect-in-php
To develop the thisPageRequiresAuthentication function there are different options, just depends what you want and what you already are using. In a lot of cases, such as if you were using a framework or a routing engine, then you'd likely handle it a little differently, but a simple solution assuming you are not doing that but are still just learning would be to just have a list of page names that don't need to be authenticated (or a list that does whitelist vs blacklist) and compare the current page being requested to that list to determine if it's need authenticated.