0
votes
if( isset($_COOKIE['user']) && !empty($_COOKIE['user']) ){
    header("Location: ./");
}

This is my code for login page. What I want to achieve is whenever someone is logged in [if a cookie named user exists], the user should be redirected to the homepage. I am using mod_rewrite to write URLs.

The problem I am facing is that whenever the cookie exists, and I go to localhost/project/login/, it shows ERR_TOO_MANY_REDIRECTS:

ERR_TOO_MANY_REDIRECTS

However when I use localhost/project/login.php it works fine.

1
if you downvote ... please let me know the reason ... I am trying to learn here ... and I have also went through stackoverflow and google. - kalpeshshende
is the homepage also doing a redirect back to login at all? - nealio82
@nealio82 : when i click on log in button from the homepage, and if cookie exists, it redirects back to login page... works well !! - kalpeshshende
"it redirects back to login page... works well" - although at the top of your question you said "the user should be redirected to the homepage". - Which should it be? The login page or the homepage? What is the URL when you click on the login button? - MrWhite

1 Answers

1
votes
header("Location: ./");

./ is a relative URL. Consequently if you send back Location: ./ in the HTTP response then the browser will interpret this as relative to whatever is currently displayed in the browser.

So...

When requesting localhost/project/login/ (note the trailing slash), the browser will redirect back to localhost/project/login/ (the same URL - redirect loop).

When requesting localhost/project/login.php, the browser will redirect to localhost/project/ (your home page I assume).

To always redirect back to the homepage (/project/) from any URL-path depth then you would need to at least specify a root-relative URL in the Location header. For example:

header('Location: /project/');

(Or, you mess around calculating the current path depth from the request in order to construct a relative URL-path. But if you are going to do that then you might as well calculate the absolute URL of the homepage - or have this stored - which is arguably preferable.)