Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

In your check_login page I don't see either session_start and the code for saving username into session so that you can retrieve it on the other page.

In check_login page please add:

session_start();

at the start and then set:

$_SESSION['username'] = $username;

so that you can retrieve and display it on the other page.

Please check following points.

  • Make sure you set username in the Session variable.

From your code, I do not see any line like following:

$_SESSION['username'] = $username

Without setting, you can get nothing.

  • If you did session_start() before using $_SESSION variable.

session_start() is required function to be called if you gonna use $_SESSION variable.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top