Header redirect not working in wp

I am inserting a snippet at the top of my WordPress page to test whether a user has logged in. I want to redirect the user if the user has not logged in. I created the following snippet. I can call it from the editor so it appears to function. I get no errors but do not get a redirection or an error when not logged in. I presume I am not seeing the error due to being in Wordpress and am guessing I cannot do this as parts of the page have already been written and I am not redirecting at the top of the code before anything has been written. Does anyone have a workaround for redirecting the user? Or maybe I just need to find a plugin to test for login?

<?php
if(isset($_SESSION['sessionId'])) {
echo "you are logged in";

} else {

header ("location: index.php?error=Mustlogin");
}

The html document is not the place to be executing a redirect. The html document is for producing the content that the visitor sees. What content should a logged in visitor see - an indication of being logged in and how about a log out link? What content should a non-logged in visitor see - how about a login link AND a registration link?

BTW - every header() redirect needs an exit; statement after it to stop php code execution. If this redirect is for security purposes, to prevent access to a page, all the php code on the rest of the page is still executed while the browser is preforming the redirect.

I was just trying to get this piece to work. I guess I could put it in the header but didn’t want all pages to require being logged in. If I can figure out how to get the page name, I can just make exceptions for login, registration and the few pages that don’t require login.

I wasn’t aware I needed an exit after the redirect. I thought that was the exit. I will have to add that to a number of my pages. Thank you.

Sponsor our Newsletter | Privacy Policy | Terms of Service