PHP – $SESSION Variables

$

Session Variables allow you to set Variable Values that can be accessed across all pages that your user goes to in your PHP Web Application.

You must use session_start() on all pages that will access or use Session Variables and then you can access the Variables from $_SESSION[‘variable_name’]

$_SESSION

home.php

<a href='/home.php'>Home</a>
<a href='/about.php'>About</a>
<a href='./anotherPage.php'>Another Page</a>
<a href='./logoutScript.php'> --- LOGOUT ---</a>
<br><br>

Please Log In:
<form action='loginScript.php' method='post'>
Name: <input type='text' name='username'>
Font Size: <input type='number' name='fontsize'>
<input type='submit'>
</form>

<?php

session_start();

$username = $_SESSION['username'];
$fontsize = $_SESSION['fontsize'];

echo "<strong>".$username."</strong> is logged in";

echo "<p style='font-size:".$fontsize.";'>This is text on the HOME PAGE.  Look at what the size is!!!</p>";

?>

loginScript.php

<a href='/home.php'>Home</a>
<a href='/about.php'>About</a>
<a href='./anotherPage.php'>Another Page</a>
<br><br>

<?php

session_start();

$_SESSION['username'] = $_POST['username'];
$_SESSION['fontsize'] = $_POST['fontsize'];

echo "You are now logged in as: ".$_SESSION['username']."<br>";
echo "You set the fontsize to: ".$_SESSION['fontsize']."<br>";
echo "Go to the Other Pages to see how SESSION VARIABLES Work";

?>

logoutScript.php

You have been logged out.
<br>
<a href='./home.php'>HOME</a>

<?php

session_start();

session_unset();

session_destroy();

?>

about.php

<a href='/home.php'>Home</a>
<a href='/about.php'>About</a>
<a href='./anotherPage.php'>Another Page</a>
<a href='./logoutScript.php'> --- LOGOUT ---</a>
<br><br>

<?php

session_start();

$username = $_SESSION['username'];
$fontsize = $_SESSION['fontsize'];

echo "<strong>".$username."</strong> is logged in";

echo "<p style='font-size:".$fontsize.";'>This is text on the ABOUT PAGE.  If I wasn't a mushroom I could write something here amazing!</p>";

?>

anotherPage.php

<a href='/home.php'>Home</a>
<a href='/about.php'>About</a>
<a href='./anotherPage.php'>Another Page</a>
<a href='./logoutScript.php'> --- LOGOUT ---</a>
<br><br>

<?php

session_start();

$username = $_SESSION['username'];
$fontsize = $_SESSION['fontsize'];

echo "<strong>".$username."</strong> is logged in";

echo "<p style='font-size:".$fontsize.";'>This is text on ANOTHER PAGE.  Imagine the I wrote something witty and profound here!</p>";
?>

Be the first to comment

Leave a Reply