I have one login form when user give username and password it leads to login.php
file
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
echo "query successfull wrote to DB";
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
echo "unscccessful login";
header('location:index.php');
}
}
When I Try to print the session by print_r($_SESSION)
from this file.. it shows the session and its variable with values
Array ( [userNameSession] => full name [loginStatus] => 1 )
In my admin/admin.php
(opens when successful login) wrote
session_start();
print_r($_SESSION);exit;
if try to print the session by print_r($_SESSION)
it shows empty array as Array()
Please help.
Why do you make an unset($_SESSION)
? This may cause the session variable is deleted but the session still exists.
If you want to clean $_SESSION['LoginStatus']
and $_SESSION['userNameSession']
, better clean one by one (although this is not necessary because you'll rewrite its value later):
unset($_SESSION['LoginStatus']);
unset($_SESSION['userNameSession']);
The code must be like this:
session_start();
if ( !empty($_POST['username']) && !empty($_POST['password']) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " YOUR QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
if (mysql_num_rows($result) > 0) {
//DELETE prints BEFORE header()!! -> echo "query successfull wrote to DB";
$row = mysql_fetch_assoc($result);
unset($_SESSION['userNameSession']);
unset($_SESSION['loginStatus']);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
//DELETE prints BEFORE header()!! -> echo "unscccessful login";
header('location:index.php');
}
}
One important thing that you must notice:
Don't echo before header. I think your code should be like this:
session_start();
if ( isset( $_POST['username'], $_POST['password'] ) ) {
$user = $_POST['username'] ;
$pass = $_POST['password'] ;
$query = " MY QUERY ";
$result = mysql_query($query) or die('SQL ERROR:'.mysql_error());
$row = mysql_fetch_assoc($result);
if ($row) {
unset($_SESSION);
$userName = $row['firstname'].' '.$row['lastname'];
$_SESSION['userNameSession'] = $userName;
$_SESSION['loginStatus'] = '1';
header('location:admin/admin.php');
}else{
header('location:index.php');
}
}
Hope this helps.