简体   繁体   中英

Php redirect doesn't work

I'm doing a project in php mvc but without framework. I organized the files in this way:

  • Directory public: there are files accessible from the outside
  • Directory View: there are files .php but essentially only html
  • Direcory Model: contains the files related to the database connection, and classes that define the objects, for example, the class User.php
  • Directory Controller: contains a 'generic' class Controller and Controller classes more 'specific'

I creat a login page (View/login.php) with a form whose action value is public/index.php. In index.php there is this code:

$controller = new LoginController();
$view = $controller->invoke();
$view->render();

invoke() is a function in Controller/LoginController.php that reads the data entered by the user and controls them, if they are correct (there is user in the database with the username and password) then creates two global variables and make a redirect:

 $_SESSION['logged_in'] = 1;
 $_SESSION['username'] = $username;
 $url = "../public/home.php";
 header("Location: $url", true, 302);
 exit();

public/home.php does this:

$controller = new HomeController();
$view = $controller->invoke();
$view->render();

HomeController is a class that extends Controller. The constructor of Controller see if there are the variables $_SESSION['logged_in'] and $_SESSION['username']. If they not exists it makes a redirect to public/index.php.

My problem is that the row with header("refresh:0; url=../public/home.php "); does not redirect.

Explain: when I insert the correct data (registered user) redirects for a short time but then returns to home.php. Instead it should redirect to home.php and stay there, do not go to index.php .

I also tried with header("refresh: 0; url = ../public/home.php"); but it's the same problem.

How can I solve this problem? Thank you and sorry for my poor English!

Add php ob_start() function on top of the page. If you call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

Ref: http://in2.php.net/ob_start

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM