Using Sessions in PHP - Another Example (Page 4 of 5 )
Still don’t understand how to use sessions? Here is another example for you. Let’s make an online user counter using sessions.
Step 1: Make a database table with 2 fields:
NAME TYPE onlineuser_session varchar(100) onlineuser_time varchar(30)
Step 2: Download the dbal from my site: here .
Step 3: Make these files
<?php // counter.php class counter { var $db; var $sid; var $dbtable; var $online; function counter () { global $db, $tblcounter; $this->db = $db; $this->table = $tblcounter; $this->sid = session_id(); $this->do_count(); } function do_count () { if ($this->is_logged()) $this->update_log(); else $this->new_log(); $sql = "SELECT COUNT(onlineuser_session) as total " . "FROM {$this->table} " . "WHERE onlineuser_time=’".(time()-60)."’"; $this->db->Query ($sql); $RS = $this->db->FirstRow(); $this->online = $RS["total"]; } function new_log () { $sql = "INSERT INTO {$this->table} " . "(onlineuser_session, onlineuser_time) " . "VALUES (‘{$this->sid}’,’".time()."’)"; $this->db->Query ($sql); } function update_log () { $sql = "UPDATE {$this->table} " . "SET onlineuser_time=’".time()."’ " . "WHERE onlineuser_session=’{$this->sid}’"; $this->db->Query ($sql); } function is_logged () { $sql = "SELECT * FROM {$this->table} " . "WHERE onlineuser_session=’{$this->sid}’"; $this->db->Query ($sql); if ($this->db->RowCount>0) return true; else return false; } }; ?>
<?php // index.php require_once("dbal.php"); require_once("counter.php"); session_start(); $db = new dbMySql ("hostname", "username", "password", "database"); $counter = new counter; print $counter->online; ?>
That’s all you need to build an online user counter. With that data, you can modify and add more functions to the counter class. Let’s say you want to make a statistic of your daily visitors. Or weekly, monthly, or maybe you can add 1 more field on the database to know what page that the user is on right now, just like on the bottom left of Codewalkers.com.
Next: Conclusions >>
More Miscellaneous Articles More By Hermawan Haryanto
Please enable JavaScript to view the comments powered by Disqus. blog comments powered by