PHP User online tutorial

This tutorial show you php script that count how many users are active on your site.


In this tutorial, create 1 PHP file for testing this code.
1. user_online.php

1. Create table "user_online" in mysql in database "test".
2. Create file user_online.php.

STEP1: Create table "user_online"

CREATE TABLE `user_online` (
`session` char(100) NOT NULL default '',
`time` int(11) NOT NULL default '0'

STEP2: Create file - user_online.php

############### Code


$time_check=$time-600; //SET TIME 10 Minute

$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="user_online"; // Table name

// Connect to server and select databse
mysql_connect("$host", "$username", "$password")or die("cannot connect to server");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name WHERE session='$session'";



$sql1="INSERT INTO $tbl_name(session, time)VALUES('$session', '$time')";

else {
"$sql2=UPDATE $tbl_name SET time='$time' WHERE session = '$session'";

$sql3="SELECT * FROM $tbl_name";


echo "User online : $count_user_online ";

// if over 10 minute, delete session
$sql4="DELETE FROM $tbl_name WHERE time<$time_check";

// Open multiple browser page for result

// Close connection


Similar Post

PHP Script Image of the day

In this script shows you how to display image of the day. You can adapt this script to display quote of the day, knowledge of the day or something else you want. You don't have to change image everyday just change images once a week.

Alternating table row colors

Many of websites use this script to alternate their table row color that selected from mysql database, very useful and cool.