MrNiceGuy
MrNiceGuy

Reputation: 13

Maintaining PHP Session Variables

I would like to maintain 3 $_Session variables after login. My login modal submits to my index.php page and this seems to be the only place I can access the session variables I set when the user logs in. How do I pass these variables to the next page the user visits? I know I can use hidden inputs in forms but what if the brows the site using the menu? I would like to store a users session variables in a session include file but I have the same issue passing the values of the variables from page to page.

-Mike

Upvotes: 0

Views: 1468

Answers (4)

MrNiceGuy
MrNiceGuy

Reputation: 13

All who have provided answers thank you. This overlooked detail was all on me and though I have been out of the dev game for a while I should have known better.

My hosting service by default makes all file permissions read/write only...to access session variables I changed to read/write/execute and was successful.

Again thanks!

Upvotes: 0

Hans
Hans

Reputation: 497

The form of your modal

<form action="index.php" method="post">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
</form> 

Then you catch it in your index.php

<?php
session_start();

if (isset($_POST['username']) && isset($_POST['password'])) {
    // Check if user exists and password matches

    $_SESSION['username'] = $_POST['username'];
    $_SESSION['logintime'] = time();
    $_SESSION['something'] = 'else';
}

In any other page you can use the values like

<?php
session_start();

if (isset($_SESSION['username'])) {
    echo 'Welcome ' . $_SESSION['username'];
}

Upvotes: 0

Yogendra
Yogendra

Reputation: 2234

You can store you values in session on one page(index in your case as you mentioned) then later on you can get those values on any page if session in started on that page. Session store those value till same session alive.

code to set values in session:

<?php
// Start the session
session_start();
?>
    <?php
    // Set session variables
    $_SESSION["xyz"] = "xyz";
    $_SESSION["abc"] = "abc";
    echo "Session variables are set.";
    ?>

Code to get session values:

<?php
// Echo session variables that were set on previous page
echo "value of xyz is " . $_SESSION["xyz"] . ".<br>";
echo "value of abc is " . $_SESSION["abc"] . ".";
?> 

Upvotes: 2

Piskvor left the building
Piskvor left the building

Reputation: 92752

File a.php:

<?php
session_start();

$_SESSION['saveme'] = 'from file A';

?>

File b.php:

<?php
session_start();

echo $_SESSION['saveme']; // if you visited a.php previously, you will see "from file A"
?>

Setting a session variable in any file makes it available anywhere else.

Upvotes: 3

Related Questions