Redirect does not work when user logs in
I made an OO entry in php. Everything works great with sessions and everything else. The only problem I ran into was my redirect not working after user login and after user registration. I'm pretty sure because I'm using the title tag, but I'm not sure how. I tried using jscript for the redirect but didn't have anything good with it.
Here's my login code (this should redirect the user to the "index.php" page):
<title>D2W Embroidery & Print</title>
<?php require 'includes/header.php'; ?>
<?php include 'includes/nav.php'; ?>
<div id="content" class="two-thrids columns">
<h3>Log In</h3>
<?php
if(session::exists('home')) {
echo '<p>', session::flash('home'), '</p>'; //displays message after users has register which is removed after page refresh
}
if(input::exists()) {
if(token::check(input::get('token'))) {
$user = new user();
$remember = (input::get('remember') === 'on') ? true : false; //detects if users has ticked the remember me box
$login = $user->login(input::get('username'), input::get('password'), $remember);
if($login) {
redirect::to('index.php');
} else {
echo '<p>Sorry, that username and password wasn\'t recognised.</p>';
}
}
}
?>
<form action="" method="post">
<div class="field">
<label for="username">Username:</label>
<input type="text" name="username" id="username">
</div>
<div class="field">
<label for="password">Password:</label>
<input type="password" name="password" id="password">
</div>
<div class="field">
<label for="remember">
<input type="checkbox" name="remember" id="remember">Remember me
</label>
</div>
<input type="submit" value="Log in">
<input type="hidden" name="token" value="<?php echo token::generate(); ?>">
</form>
and this is the code to redirect:
<?php
class redirect {
public static function to($location = null) {
if($location) {
if(is_numeric($location)) {
switch($location) {
case 404:
header('HTTP/1.0 404 Not Found');
include 'includes/errors/404.php';
exit();
break;
}
} else {
header('Location: ' . $location);
die();
}
}
}
}
?>
This is the javascript redirect I tried. I've never used this before, so not sure if I'm doing it right.
echo '<script type="text/javascript">
window.location = '. $location .'
</script>';
die();
Any help would be great.
source to share
Just add ob_start () to the beginning of your file.
Explanation:
Your redirect doesn't work because you are printing HTML on the page before the redirect.
No redirection happens if you have an exit on the page.
If we use ob_start()
, all printed output will be stored in a buffer and can be found later.
And a redirect happens.
source to share