Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
594 views
in Technique[技术] by (71.8m points)

php - Error: localhost redirected you too many times. ERR_TOO_MANY_REDIRECTS

I have my framework set up as MVC type, where a core library redirects url. This is useful say if a link is as: Some_class/some_method, it will load some_method from Some_class. Also I have configured everything to pass through index.php using .htaccess file.
Code in index.php

<?php
session_start();
require_once 'config.php';
if (!isset($_SESSION['username']) && empty($_GET['url'])) { ?>
    <a href="Users/login">Login</a><br>
    <a href="Users/register">Register</a>
<?php } ?>

Code in config.php

// Redirect to the homepage if not signed in
    if(!isset($_SESSION['user'])){
     header('location: http://localhost/index.php');
 }

Code in Users Controller

public function login(){
    // Code to verify the entered credentials
    // If entered data is valid
    $_session['user'] = $_POST['user'];
}
public function log_out(){
    session_unset();
}

If someone logs out using log_out method from users controller, the method executes. And if the code were right ideally it should redirect to index.php, because the code in config.php says that if $_SESSION['user'] is not set, it should redirect to index.php. However, whenever someone logs out I get the error mentioned in the title. What mistake am I doing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's happening because you have a redirect loop. This is what's happening.

  1. User logs out and session is unset
  2. User is then redirected to index.php where you call "config.php"
  3. In config.php you check if the user is not logged in. He's not so it tells it to redirect to index.php (and you're back at point 2 again and round and round you go)

Change you config.php to redirect if the user IS logged in e.g.

// Redirect to the dashboard signed in
if(isset($_SESSION['user'])){
 header('location: http://localhost/dashboard.php');
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...