Reputation: 93
so I made a simple user log in website, and I want to set a cookie so that when they come back to the website, it will take them to the members area and not the main page, kind of like a "remember me" function that redirects users to a members area if a cookie is set.
Problem I am facing: The php code right before the html code does not redirect to the member.php page even though the cookie is set!
Note: I'm just using parts of the code, and not the entire code/ other files to simplify the question.
here's my code:
main.php (this is the main page, and also where the log-in form is, but log in form is not shown)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<?php
//Checks if there is a login cookie
if(isset($_COOKIE["blablabla"])) //if cookie is set
{
header("Location: www.website.com/member.php"); //redirect to member.php
}
else
{
//otherwise, redirect to nocookiefound.php
header("Location: www.website.com/nocookiefound.php");
}
?>
<html>
<body>
<?php
echo "Welcome " . $_COOKIE["blablabla"] . "!<br />";
//I ran a echo test to see if cookie is still there, and it is.
?>
</body>
</html>
So my question is, can my redirect work the way it is?
I must be doing something wrong because it's not redirecting to member.php even though the cookie echos the correct value.
So, if i was originally in the members.php page after I logged in, then go back to main.php, it SHOULD redirect me to members.php, but it doesn't, it just stays at main.php. Anyone know what's going on? I would appreciate all the help I can get. Thanks
Upvotes: 0
Views: 858
Reputation: 72975
In addition to the other answers, put an exit(); after the header lines. It's possible to write a script that ignores headers, hence running the other code inadvertently.
People often use headers to protect admin areas without realising that.
Upvotes: 0
Reputation: 28795
As well as what @Dogbert says, your redirection is invalid. Try:
header("Location: http://www.website.com/member.php");
Upvotes: 0
Reputation: 222040
The PHP code should be the first thing on the page, as you're sending a redirect "Header". Move it to before the Doctype declaration.
Upvotes: 1