Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Too many redirects #39

Closed
crichardson9 opened this issue Jul 12, 2017 · 2 comments
Closed

Too many redirects #39

crichardson9 opened this issue Jul 12, 2017 · 2 comments

Comments

@crichardson9
Copy link

crichardson9 commented Jul 12, 2017

If we take the following code:

$router->before('GET', '/.*', function() {
    if (!isset($_SESSION['user'])) {
        header('location: /login');
        exit();
    }
});

How would one stop a redirect loop when '/login' is requested?

@sigee
Copy link

sigee commented Jul 13, 2017

@crichardson9,
Maybe there is a better way, but you can check the $_SERVER['REQUEST_URI']

$router->before('GET', '/.*', function() {
    if ($_SERVER['REQUEST_URI'] != '/login' && !isset($_SESSION['user'])) {
        header('location: /login');
        exit();
    }
});

@bramus
Copy link
Owner

bramus commented Jul 14, 2017

In addition to @sigee's answer – which does the job just fine – you could also make use of the fact that the parts of dynamic routes can be converted to variables/parameters in the callback (see Route Patterns)

$router->before('GET', '/(.*)', function($path) {
    if ($path !== 'login' && !isset($_SESSION['user'])) {
        header('location: /login');
        exit();
    }
});

Additionally it might be a good idea to not check for equality, but to check if $path starts with login or not.

@bramus bramus closed this as completed Jul 14, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants