We're all familiar with users-online counters, some of us can make our own, some of us can go onto Tutorialized or Good Tutorials and follow basic instructions in order to have them - but what about those just starting? What about people who don't have fancy-pants PHP and only have access to things like freewebs? What do they do?
There's a clear niche in the market where other site tool websites just haven't bothered. It's weird, online-user counters are tools that new and experienced webmasters alike use to get an idea of how many people visit their sites, it's something everyone requires but not everyone can get. In this tutorial you will learn how to create your own online-users counter hosting script (what a mouth full!) so that you can fill this niche. You'll learn how to make a PHP online-users counter and adapt this to display in javascript, allowing anyone with or without PHP to display their online counters from your site! Without further ado let's begin.
The plan
As usual I'm going to try and keep things simple, we're going to run the whole site off 2 simple pages:
- online_create.php - This is where your user will enter their info and create their guestbook.
- online_view.php - This is where your users code will be displayed from.
And that's the plan really.
In the beginning... Like when ganesh (oh get on with the story) ok ok.
Well we're not getting anywhere fast without creating our mySQL table, we need to run the following query, the whole script will run off this!
PLAIN TEXT
SQL:
- CREATE TABLE `online` (
- `id` int(11) NOT NULL AUTO_INCREMENT,
- `ip` varchar(15) NOT NULL DEFAULT '',
- `time` varchar(11) NOT NULL DEFAULT '',
- `url` varchar(80) NOT NULL DEFAULT '',
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=130397 ;
So in this we create the table "online" with four fields; "id", a field that increments by 1 everytime a row is added; "ip", this is how we tell if a hit is a unique user and not just the same one; "time", this tells us how old a row so we can delete it after 5 minutes and finally "url", this is so we know if the ip is on the same site or not therefore it works if the users visit several sites hosted by you!
Now you need to connect to this database via the php, you could use your own method if you're integrating this with another site or you can use this method, you need to put this on online_view.php only:
PLAIN TEXT
PHP:
- // Database
- $db_host = "localhost"; //Mysql Host
- $db_login = "yourname_username"; //Mysql username
- $db_pass = "password"; //Mysql password
- $db_name = "yourname_database"; //Mysql database This can be a existing database.
- openDB();
- function openDB()
- { global $db,$db_host,$db_login,$db_pass,$db_name;
- $db=mysql_connect("$db_host","$db_login","$db_pass");
- mysql_select_db("$db_name",$db);
- }
online_view.php
I've started with online view as it will make the other easier to explain. I'm going to annotate the script rather than tit about repeating myself afterwards.
PLAIN TEXT
PHP:
- <?
- /*
- This is pretty simple stuff to be honest, in this file we will get the users details
- submit the fact they're online to the database then display this in Javascript form
- using the PHP Header() function and Javascript's document.write()!
- Please note: my online users script is based on "Users online" by bs0d, it has been
- adapted for hosting. Checkout www.allsyntax.com for info.
- */
- // DATABASE CONNECT HERE
- Header("content-type: application/x-javascript");
- // We change the filetype to appear like Javascript
- $ip1 = $_SERVER['REMOTE_ADDR'];
- // We get the users IP address
- $time = time();
- // We get the current time
- $url = $_GET['url'];
- // We get the URL of the site being visited
- $ip_check = 'SELECT ip FROM `online` WHERE ip = \''.$_SERVER['REMOTE_ADDR'].'\' AND url = \'' . $url . '\'';
- // We check if the IP is already present with the URL on the database
- $ip_query = mysql_query($ip_check);
- // Execute this check
- $num_rows = mysql_num_rows($ip_query);
- // We count the number of results, if there are then we know it's not a unique hit, if there aren't then we can continue to add to the database.
- if(!$url) {
- // If the user hasn't provided their URL then why should we host 'em?
- echo "document.write(\"Err.No URL\")";
- // Tell them "no!"
- } else {
- // If they have, it's an entirely different case!
- if(!$num_rows) {
- $insert_new = mysql_query("INSERT INTO `online` (ip, time, url) VALUES ('$ip1', '$time', '$url')");
- // If the result to the above was null then we insert the users unique hit at the current time
- }
- if($num_rows> 0) {
- $update = mysql_query('UPDATE `online` SET time=\''.time().'\' WHERE ip = \''.$_SERVER['REMOTE_ADDR'].'\' AND url=\'' . $url . '\'');
- // If the user is already counted as being online then simply update the time they were last active at.
- if(!$update) die(mysql_error());
- // Execute this
- }
- $delete_old = mysql_query("DELETE FROM `online` WHERE ((".time()."-time)> 300)");
- // While this script is running we'll check and delete any records older than 300 seconds (5 minutes)
- if(!$delete_old) die(mysql_error());
- }
- // So above was all the counting stuff, now we need to display the user count on the site, you could offer an alternative code for users to keep this hidden and only display on stats pages .etc.
- $id_query = @mysql_query("SELECT * FROM `online` WHERE url='" . $url . "'");
- $counter = mysql_num_rows($id_query);
- echo("document.write(\"$counter\");");
- // Query the SQL for counts for that site
- // Display the counts in javascript: docment.write("10") for example.
- ?>
So basically that's the handling of the counter, the important part - the next part is pretty damned simple.
online_create.php
PLAIN TEXT
PHP:
- <?
- $site = "http://www.yourdomain.com/path/to/hosting/script/";
- // Just to make life simple for the tutorial with forward slash.
- if(!$_POST['url'])
- // If they've not submitted a URL then display the form.
- {
- ?>
- <form method="POST">
- Your URL: <input type="text" name="url"/><br />
- <input type="submit"/></form>
- <?
- } else {
- // If they've submitted a URL then give them their website code
- ?>
- Copy and paste this code onto your website:<br />
- <textarea cols="41" rows="6"><!-- Begin YOURWEBSITE.com counter Code -->
- <script src="<? echo $site; ?>online_view.php?url=<? echo $_POST['url']; ?>" type="text/javascript"></script>
- <!-- End YOURWEBSITE.com counter Code --></textarea>
- <?
- }
- ?>
That page simple generates the code to use to view your counter.
Conclusion
Yep so that's it! Easy eh? There's a fair few things you could adapt this to do, you could put the website addresses in a database so you have an idea of just how many sites're using your counter script, you could offer different styles, perhaps replacing the numbers with images, offering graphical counters .etc. You could add a "provided by" link or have the counter link to your page - there's just tons you can do, give it a try!
discuss this topic to forum
