Simen_257 Simen_257 - 1 month ago 17
PHP Question

PHP getting session username

Im trying to get the username of the logged in user from session. I can alert roomnumber and id of the user, but not the username.

Code for storing:

session_start();
$con = DbConnect();
if (isset($_POST)) {
$username = $_POST['username'];
$pwd = $_POST['password'];
$sql = 'select id, username, password, roomNr from room where username = "' .$username. '"';
$result = mysqli_query($con, $sql);
$count = mysqli_num_rows($result);
$userData = mysqli_fetch_array($result, MYSQLI_ASSOC);

if ($count == 1) {
session_regenerate_id();
$_SESSION["sess_id"] = $userData['id'];
$_SESSION["sess_username"] = $userData['username'];
$_SESSION["sess_room"] = $userData['roomNr'];
session_write_close();
header("location: ../main_page.php");
} else {
header('index.php');
}


Code for retrieving:

echo $_SESSION['sess_username'];


NOTE: This is just a quick test to see if i can get the spesific problem working. I am not going to use the above code in the final product.

Solution: The problem wasn't with the php, it had to do with how i used the variable in the script tag.

The working solution:

var user = '<?php echo $_SESSION['sess_username']; ?>';

TED TED
Answer

What my suggestion is, assign your user data to a session array and retrieve. that would not loose your data

     session_start();
     session_regenerate_id();
     $_SESSION["user_data"] = $userData;
     session_write_close();

And also make sure you are including session_start() in all your include files.

Comments