Sessions and cookies are a type of way for people to stay "logged in" on any PHP-enabled web site hosting efficently without having to re-login every time they close the browser or even refresh the page. Cookies are pretty more up to date than sessions but are a little more complicated to use; but of course very easy to learn. In this tutorial, however I will be covering sessions - to an extent they're better than cookies because they only stay there until the user closes the browser and after, they'll need to re-login but cookies would stay on the user's computer until they clear their cookies from the browser's Tools menu.
I presume you already are familar with PHP syntax, etc so let's get straight down to the function that starts a session in PHP:
PHP Code:
<?php
session_start();
?>
<html>
<head>
<title>PHP Sessions</title>
</head>
<body>
</body>
</html>
Now basically here the session_start() function is to start a session in PHP and is always required generally before anything else on a Web page, or to be more precise - before anything that outputs (like header() function, etc).
Now, create an HTML form like so:
Code:
<form action="index.php">
<input type="text" name="message">
</form>
Just for convenience for people who are not familar with XHTML I won't be putting extra code that is required for XHTML validity just incase you aren't familar with it. Now, on the same index.php file, just below that HTML code, paste this chunk of PHP code:
PHP Code:
<?php
$_SESSION['Session'] = $_POST['message'];
echo $_SESSION['Session'];
?>
And this will display the text they entered in the form persistently regardless how many times the user refreshes as the message has been saved into a session - so until they close their browser, that will be displayed on the page - and that's one form of a dynamic Web page!
So, for reference these are the things you'll generally need for sessions:
- $_SESSION['SessionName'] = value;
- session_start();
Now the value in the session variable could be the user's logged in username or if you're making an
e-commerce application - the item ID the person wanted to save to come back to - but for
e-commerce hosting apps in this case, cookies may be more convenient just in-case the user closes their browser. But in most cases sessions would be best as they're more convenient for safety especially for people who use shared computers, etc. But, using either sessions or cookies is entirely up to you. You can get more information on cookies in PHP at php.net/cookies and sessions at php.net/sessions.
Remember references of
the massive array of functions in PHP are available at
www.php.net/function_name and PHP is available with hosting at eUKhost

.