user3129080
user3129080

Reputation:

Php redirect doesn't work

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

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!

Upvotes: 1

Views: 262

Answers (1)

Krish R
Krish R

Reputation: 22711

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: https://www.php.net/ob_start

Upvotes: 3

Related Questions