You are on page 1of 3

Using sessions

<?php
/*Start the session. A session creates a file in a temporary directory on the server where registered session variables and their values are
stored. They are more secure than cookies, which are stored on the client-side machine*/
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php

//Set session variables


$_SESSION["firstname"] = "Morag";
$_SESSION["lastname"] = "Kelly";
echo "Session variables are set.";
?></body></html>
Save as exercise1.php

<?php
session_start();
?>

1|Page
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "My first name is " . $_SESSION["firstname"] . ".<br>";
echo "My second name is " . $_SESSION["lastname"] . ".";
/*Most sessions set a user-key on the user's computer that looks like an encrypted password. Then, when a session is opened on another
page, it scans the computer for a user-key. If there is a match, it accesses that session, if not, it starts a new session*/
?></body></html>
Save as exercise2.php

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();

2|Page
// destroy the session
session_destroy();
echo "The session is now destroyed. Try running exercise 2 to see the result.";
?></body></html>
Save as exercise3.php

Using the trim function


<?php
$str = "HNC Computer Science!";
echo $str . "<br>";
echo trim($str,"He!");
?>
Save as exercise4.php

3|Page

You might also like