Reputation: 15
I have the following code which logs someone in to my page - what I am trying to figure out is how to adjust it so that once it has validated that they are a good login, it forwards them to a different page.
session_name('wpLogin');
// Starting the session
session_set_cookie_params(2*7*24*60*60);
// Making the cookie live for 2 weeks
session_start();
if($_SESSION['id'] && !isset($_COOKIE['wpRemember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the wpRemember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM tz_members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('wpRemember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
exit;
Upvotes: 0
Views: 66
Reputation: 4291
You need to use the header
function. The documentation can be found here: http://php.net/manual/de/function.header.php
In short, use this:
if($row['usr']) {
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('wpRemember',$_POST['rememberMe']);
header("Location: index.php");
}
Please remember, that ANY header
function can only work if it's called BEFORE there's a single sign output to the browser.
That includes echo
or anything outside of the PHP tags. Also, please take care, that your source files don't have a BOM in it's formatting, since that would cause header
to fail too.
Upvotes: 1