Search code examples
phpsession-variableslogin-script

Displaying username using $_SESSION['username']


When I try to display the username of a logged-in user I get 'Welcome, 1' where 1 should be the username of the person logged in. This is my code in the members.php. The commented out line doesn't work either.

<?php
require_once('include.php');
?>
<?php
// echo "welcome, {$_SESSION['username']}";     
$user = $_SESSION['username'];

echo "Welcome $user";

?>

The user is logged in, I wonder if I've made a mistake in the check-login page. The code for the check_login page is:

<?php 
require_once('include.php');

$username = trim($_POST['user']);
$password = trim($_POST['pass']);

$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);

$sql="SELECT * FROM user WHERE username='$username' and password='$password';";
$result = mysql_query($sql);

$count = mysql_num_rows($result);

if($count !== 0){

$_SESSION['logged-in'] = true;
header("location:members.php?user=$username");
exit; 
}
else {
$_SESSION['logged-in'] = false;
header("location:login_again.php");
exit;
}
?>

which redirects to the members.php page upon successful login. Anybody have any ideas why the username is '1' everytime? Many thanks


Solution

  • there needs to be a session_start() somewhere at the top of your code

    <?php session_start();
    require_once('include.php');
    ?>
    <?php
    // echo "welcome, {$_SESSION['username']}";     
    $user = $_SESSION['username'];
    
    echo "Welcome $user";
    
    ?>
    

    you also need to set it before accessing it with session_start at the top of this file also

    if($count>0){
    $_SESSION['username']=$username;
    $_SESSION['logged-in'] = true;
    header("location:members.php?user=$username");
    exit; 
    }
    

    your code is open for sql injection attacks, Use prepared statements instead