UK WEB HOSTING FORUM FOR DISCUSSION ON WEB HOSTING SERVICE AND SUPPORT
LINUX HOSTING WINDOWS HOSTING PACKAGES SHOPPING CART OSCOMMERCE ZEN CART AGORA
ECOMMERCE HOSTING ASP MSSQL FRONTPAGE HOSTING PHP MYSQL HOSTING DISCUSSION FORUM
CPANEL RESELLER HOSTING DEDICATED SERVER VPS HOSTING PLESK VIRTUOZZO
Quick Search
Your forum announcement here!

  UK Web Hosting | Dedicated Server Windows and Linux VPS Forum > Technical Support > Tutorials / How to?

Reply
 
LinkBack Thread Tools Search this Thread Display Modes
  #1 (permalink)  
Old 23-06-2008, 20:02
Ben Ben is offline
Premium Member
 
Join Date: Jan 2007
Location: setcookie()
Posts: 1,147
Send a message via AIM to Ben Send a message via MSN to Ben Send a message via Yahoo to Ben
Default Using Sessions in PHP

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 .
__________________
dynBB.com PHP Tutorials & Webmaster Help Forums - need help? find PHP tutorials, help & more @ dynBB.com forums! CSS, PHP, MySQL & more!

Last edited by Ben; 25-06-2008 at 15:41.
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #2 (permalink)  
Old 24-06-2008, 07:33
System Administrator
 
Join Date: Dec 2006
Location: localhost
Posts: 710
Thumbs up

Hi Ben, another useful tutorial.. I'm sure this is going to be beneficial for others too.. as usual.. keep up the good work...
__________________

Rock _a.k.a._ Jack L.

http://www.eUKhost.com
Windows Hosting || Windows Reseller Hosting
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 24-06-2008, 10:41
eUK-Martin's Avatar
Windows System Administrator
 
Join Date: Nov 2005
Location: Earth
Posts: 457
Default

Hello,

Great one Ben..

I would like to add that if you are running PHP on Windows then sessions will expire if the application pool refreshes. The default idle time for a pool to get refreshed is 10 minutes. This can be easily edited from the properties of Application Pool in IIS Web Server.
__________________
Martin
Windows System Admin.


Windows VPS Hosting - Windows Dedicated Server - Web Hosting Tutorials

Email :: windows @ eUKhost.com AND support @ eUKhost.com
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 25-06-2008, 13:32
DavidAllen's Avatar
Premium Member
 
Join Date: Jan 2007
Location: Amersham
Posts: 360
Send a message via MSN to DavidAllen Send a message via Skype™ to DavidAllen
Default

Good tutorial. I would also like to add that the session data can be stored in a database, thus avoiding any problems with application pools (winows) or other possible security risks in a shared hosting environment

just create a session class
PHP Code:
class session
{
    
/* Define the MySQL Server table you wish to use with
       this class, this table MUST exist. */
    
var $ses_table "YourTableName";

    
/* Change to 'Y' if you want to connect to a db in
       the _open function */
    
var $db_con "Y";

    
/* Configure the info to connect to MySQL, only required
       if $db_con is set to 'Y' */
    
var $db_host "localhost";
    var 
$db_user "username";
    var 
$db_pass "password";
    var 
$db_dbase "database_name";

    
/* Create a connection to a database */
    
function db_connects() {
        
$mysql_connect = @mysql_connect ($this->db_host,
                                          
$this->db_user,
                                          
$this->db_pass);
        
$mysql_db = @mysql_select_db ($this->db_dbase);

        if (!
$mysql_connect || !$mysql_db) {
            return 
FALSE;
        } else {
            return 
TRUE;
        }
    }

    
/* Open session, if you have your own db connection
       code, put it in here! */
    
function _open($path$name) {
        if (
$this->db_con == "Y") {
            
$this->db_connects();
        }

        return 
TRUE;
    }

    
/* Close session */
    
function _close() {
        
/* This is used for a manual call of the
           session gc function */
        
$this->_gc(0);
        return 
TRUE;
    }

    
/* Read session data from database */
    
function _read($ses_id) {
        
$this->db_connects();
        
$session_sql "SELECT * FROM " $this->ses_table
                     
" WHERE ses_id = '$ses_id'";
        
$session_res mysql_query($session_sql);
        if (!
$session_res) {
            return 
'';
        }

        
$session_num mysql_num_rows ($session_res);
        if (
$session_num 0) {
            
$session_row mysql_fetch_assoc ($session_res);
            
$ses_data $session_row["ses_value"];
            return 
$ses_data;
        } else {
            return 
'';
        }
    }

    
/* Write new data to database */
    
function _write($ses_id$data) {
        
$this->db_connects();
        
$session_sql "UPDATE " $this->ses_table
                     
" SET ses_time='" time()
                     . 
"', ses_value='".addslashes($data)."' WHERE ses_id='$ses_id'";
        
$session_res mysql_query ($session_sql) or die('Query failed: ' mysql_error().'<br>'.$session_sql);
        if (!
$session_res) {
            return 
FALSE;
        }
        if (
mysql_affected_rows ()) {
            return 
TRUE;
        }

        
$session_sql "INSERT INTO " $this->ses_table
                     
" (ses_id, ses_time, ses_start, ses_value)"
                     
" VALUES ('$ses_id', '" time()
                     . 
"', '" time() . "', '$data')";
        
$session_res mysql_query ($session_sql);
        if (!
$session_res) {
            return 
FALSE;
        }         else {
            return 
TRUE;
        }
    }

    
/* Destroy session record in database */
    
function _destroy($ses_id) {
        
$this->db_connects();
        
$session_sql "DELETE FROM " $this->ses_table
                     
" WHERE ses_id = '$ses_id'";
        
$session_res mysql_query ($session_sql);
        if (!
$session_res) {
            return 
FALSE;
        }         else {
            return 
TRUE;
        }
    }

    
/* Garbage collection, deletes old sessions */
    
function _gc($life) {
        
$this->db_connects();
        
$ses_life strtotime("-2 hours");

        
$session_sql "DELETE FROM " $this->ses_table
                     
" WHERE ses_time < $ses_life";
        
$session_res mysql_query ($session_sql);


        if (!
$session_res) {
            return 
FALSE;
        }         else {
            return 
TRUE;
        }
    }

Then when you want to start the session just add a few lines to the tutorial above
PHP Code:
require("classes/session.class.php"); //the file with the above class code in

/* Create new object of class */
$ses_class = new session();

/* Change the save_handler to use the class functions */
session_set_save_handler (array(&$ses_class'_open'),
                          array(&
$ses_class'_close'),
                          array(&
$ses_class'_read'),
                          array(&
$ses_class'_write'),
                          array(&
$ses_class'_destroy'),
                          array(&
$ses_class'_gc'));
/* Start the session */
session_start(); 
That's it - session data stored safely in a database - with the advantage that you can query it to find out things like - who's online
__________________
David Allen - www.serina.co.uk
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 25-06-2008, 20:33
eUK-Martin's Avatar
Windows System Administrator
 
Join Date: Nov 2005
Location: Earth
Posts: 457
Default

Awesome David..
I really admire your command on PHP... Great job.
__________________
Martin
Windows System Admin.


Windows VPS Hosting - Windows Dedicated Server - Web Hosting Tutorials

Email :: windows @ eUKhost.com AND support @ eUKhost.com
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 05-08-2008, 12:03
Banned
 
Join Date: Aug 2008
Posts: 7
Default

Building web applications with membership management is one of the most frequent tasks that every programmer does. Managing membership data, such as username, password and the member's profile with sessions in PHP is the easiest and simplest solution, although it is not the only one.

Last edited by Ben; 06-08-2008 at 07:36. Reason: spammed ads
Digg this Post!Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On


All times are GMT. The time now is 16:55.

 

Powered by vBulletin® Version 3.7.2
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
LinkBacks Enabled by Web Hosting 3.1.0
Copyright © 2001-2008, eUKhost.com. All rights reserved.

 
Site Map

VPS Hosting
VPS Hosting plans

Dedicated Server Hosting
Dedicated Server plans

Business Web Hosting
100% uptime Hosting

Cpanel Hosting
cPanel Shared Hosting

Reseller Hosting
Reseller Web Hosting

Windows Hosting
Windows Shared Hosting

Windows VPS

Windows VPS Hosting

Semi Dedicated Servers
Semi-Dedicated Hosting

Dedicated Server Mirroring
Dedicated Server Mirroring

Webhosting Knowledgebase
Frequently asked Questions

Web Hosting Blog
eUKhost Blog

Web Hosting Support
Support Helpdesk

UK Data Center
eUKhost Datacenter

Web Hosting Forum
eUKhost Forum

Support Tutorials
Online Flash Tutorials

Offsite Back-up Plans
Remote Backup Service

Customer Testimonials
eUK Customer Testimonials


knowledgebase articles

eUKhost.com Services

Pre-Sales Questions
Pre-sales FAQ's

Domain Names
Domain registration FAQ's

cPanel Hosting
cPanel Hosting FAQ's

Windows Web Hosting
Plesk Control Panel

Reseller Hosting
Reseller Hosting FAQ's

VPS Hosting
Virtual Private Server

Semi-Dedicated Servers
Semi-Dedicated FAQ's

Dedicated Servers
Dedicated Server Hosting


popular blog categories


Web Hosting
Website Hosting articles

UK Web Hosting
UK Hosting articles

Dedicated Server Hosting
Dedicated Server guidelines

VPS Hosting
VPS hosting articles

cPanel Hosting
cPanel Hosting articles

Linux Operating System
Linux Operating techniques

Windows Web Hosting
Windows plesk articles

Web Hosting
Web Hosting Service