Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Counting Sessions 4

Status
Not open for further replies.

Tuck007

Technical User
Apr 29, 2002
105
US
I have recently created a small webcam page. I want to figure out a way to count how many people are viewing the webcam at any one time. I think I can do this by using sessions. When the first user begins veiwing the webcam, a session is started. Once another user begins viewing the webcam, I'll start another session. This will continue giving me X amount of users viewing the webcam at the same time. Question number 1: Can I use count() to count the amount of session? Question number 2: I want to display the amount of sessions to everyone viewing the webcam, how?

The page I'm using does not yet contain any PHP, but it will. Here is the code from the page that will be displayed:
Code:
<html>
<head>
<title>Tuck's WebCam</title>
<link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;tucknet.css&quot;>
<meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=iso-8859-1&quot;>
</head>
<!-- Script stolen from GeneriCam - [URL unfurl="true"]http://occonnect.com/johnqpublic[/URL]
     Thanks to the Nose, Sito and S.A. Dave -->
<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!-- hide

// browser sniffer:
browserVer = parseInt(navigator.appVersion);
if (navigator.appName == &quot;Microsoft Internet Explorer&quot; && browserVer < 4)
{
alert(&quot;Internet Explorer 3 users need to hit 'Refesh' to update the image&quot;);
}

//this eliminates JavaScript error messages
onError=null

// The variables you need to change are: the filename of the picture,
// the refresh rate, the expected time to download and further down,
// the FORM ACTION (look for the ***).
var picname = &quot;[URL unfurl="true"]http://www.batnet.com/ctuck/gifs/ispy.jpg&quot;;[/URL]  // set this to the filename of your campicture
var speed = 8;  // &quot;var speed&quot; is the refresh rate adjustment in seconds
var y = 1;      // expected time to download the picture file. It  MUST be
                 // set at a smaller number than the &quot;speed&quot; variable!

var x = speed;   // current countdown
var cachepic = new Image();

// Change &quot;JSCamRemoteNT.html&quot; to whatever you want to call the page that 
// opens in the remote window. 

function openremoteWindow()
	{
	stopClock();
	open (&quot;JSCamRemoteNT.html&quot;,&quot;JSCamRemote&quot;, &quot;height=310,width=340,scrollbars=0,resizable=yes,status=0&quot;)
	}

function stopClock() {
	x = &quot;00&quot;;
}

function startClock() {
        if (x != &quot;00&quot;) {
	x = x - 1;
         if (x == y) {
          recache()
        }
	if (x <= 0)
        {
          reload()
        }
	timerID = setTimeout(&quot;startClock()&quot;, 1000);
        }
}

function recache() {
      var now = new Date();
      var camImg = picname + &quot;?&quot; + now.getTime();
      cachepic.src = camImg;
    }

function reload() {
    document.images.campicture.src = cachepic.src;
    x = speed;
              	  }

//end hide -->
</SCRIPT>



<BODY>

<TABLE WIDTH=&quot;100%&quot; HEIGHT=&quot;50&quot; BORDER=&quot;0&quot; CELLPADDING=&quot;0&quot; CELLSPACING=&quot;0&quot;>
  <TR>
    <TD ALIGN=&quot;CENTER&quot; BGCOLOR=&quot;#aaddff&quot; HEIGHT=&quot;5&quot;><TABLE WIDTH=&quot;100%&quot; BORDER=&quot;0&quot; CELLPADDING=&quot;5&quot; CELLSPACING=&quot;0&quot;>
<TR><TD></TD></TR></TABLE></TD>
  </TR>
  <TR>
    <TD ALIGN=&quot;CENTER&quot; BGCOLOR=&quot;#ffffff&quot;><FONT FACE=&quot;ARIAL&quot; SIZE=&quot;6&quot; 
    COLOR=&quot;#000099&quot;><B>JavaScriptCam</B></FONT></TD>
  </TR>
  <TR>
    <TD ALIGN=&quot;CENTER&quot; BGCOLOR=&quot;#aaddff&quot; HEIGHT=&quot;5&quot;><TABLE WIDTH=&quot;100%&quot; BORDER=&quot;0&quot; CELLPADDING=&quot;5&quot; CELLSPACING=&quot;0&quot;>
<TR><TD></TD></TR></TABLE></TD>
  </TR>
</TABLE>

<!-- In the section below, change &quot;CamPic.jpg&quot; to whatever you call your cam image -->

<CENTER>
<TABLE BORDER=&quot;0&quot; CELLPADDING=&quot;0&quot; CELLSPACING=&quot;0&quot; BGCOLOR=&quot;ffffff&quot;>
<TR><TD ALIGN=&quot;center&quot;><A HREF=&quot;javascript:openremoteWindow()&quot;><IMG 
NAME=&quot;campicture&quot; SRC=&quot;[URL unfurl="true"]http://www.batnet.com/ctuck/gifs/ispy.jpg&quot;[/URL] ALT=&quot;Picture&quot; BORDER=&quot;0&quot; HEIGHT=&quot;240&quot; 
WIDTH=&quot;320&quot; RELOAD=&quot;30&quot;></A></TD>
</TR>
</TABLE>
</CENTER>
<TABLE WIDTH=&quot;100%&quot; BORDER=&quot;0&quot;>
<TR>
<TD WIDTH=&quot;100%&quot; ALIGN=&quot;CENTER&quot; COLSPAN=&quot;2&quot;><FONT SIZE=&quot;3&quot;>Click on the image for a remote window.</FONT>
<BR>
<FONT SIZE=&quot;3&quot;>PLEASE DO NOT HIT RELOAD!!</FONT></TD>
</TR>
</TABLE>

<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!-- hide
startClock()
//end hide -->
</SCRIPT>

</body>
</html>
.:TUCK:.
 
I put the wrong code in the last post. Here is the code I am using with all the PHP I'm using and my attempt at counting sessions:

Code:
<?php
if($view == &quot;html&quot;){
	header(&quot;location: [URL unfurl="true"]http://www.tuck-net.com/webcams/tuck/htmlcam/htmlcam&quot;.[/URL] $rate .&quot;.htm&quot;);
	exit;
	}
	
//Count sessions here	
$view = $view++;
session_register('view');
$countme = session_id();
$viewers = count($countme);

?>
<TITLE>
Tuck WebCam
</TITLE>
<link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;tucknet.css&quot;>
</HEAD>
<!-- Original JavaScript found at GeneriCam - [URL unfurl="true"]http://occonnect.com/johnqpublic[/URL] -->
<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
<!-- hide

// browser sniffer:
browserVer = parseInt(navigator.appVersion);
if (navigator.appName == &quot;Microsoft Internet Explorer&quot; && browserVer < 4)
{
alert(&quot;Internet Explorer 3 users need to hit 'Refesh' to update the image&quot;);
}

//this eliminates JavaScript error messages
onError=null

// The variables you need to change are: the filename of the picture,
// the refresh rate, the expected time to download and further down,
// the FORM ACTION (look for the ***).
var picname = &quot;cam.jpg&quot;;  // set this to the filename of your campicture
var speed = <?php print $rate; ?>;  // &quot;var speed&quot; is the refresh rate adjustment in seconds
var y = 1;      // expected time to download the picture file. It  MUST be
                 // set at a smaller number than the &quot;speed&quot; variable!

var x = speed;   // current countdown
var cachepic = new Image();

// Change &quot;JSCamRemoteNT.html&quot; to whatever you want to call the page that 
// opens in the remote window. 

function openremoteWindow()
	{
	stopClock();
	open (&quot;JSCamRemoteNT.html&quot;,&quot;JSCamRemote&quot;, &quot;height=310,width=340,scrollbars=0,resizable=yes,status=0&quot;)
	}

function stopClock() {
	x = &quot;00&quot;;
}

function startClock() {
        if (x != &quot;00&quot;) {
	x = x - 1;
         if (x == y) {
          recache()
        }
	if (x <= 0)
        {
          reload()
        }
	timerID = setTimeout(&quot;startClock()&quot;, 1000);
        }
}

function recache() {
      var now = new Date();
      var camImg = picname + &quot;?&quot; + now.getTime();
      cachepic.src = camImg;
    }

function reload() {
    document.images.campicture.src = cachepic.src;
    x = speed;
              	  }
function close() {
		window.close()
									}

//end hide -->
</SCRIPT>

<BODY>
<CENTER>
<h2>Tuck's WebCam</h2><br><div class=&quot;infotext&quot;>
Best viewed using latest version of Netscape or Internet Exploroer.<br>
Your browser is <?php echo $HTTP_USER_AGENT; ?></div>
</CENTER>
<hr width=&quot;50%&quot;>
<br>
<TABLE width=&quot;320&quot; border=&quot;1&quot; cellspacing=&quot;0&quot; cellpadding=&quot;0&quot; height=&quot;240&quot; align=&quot;center&quot;>
<TR>
<TD ALIGN=&quot;center&quot;>
<?php
	if($view == &quot;java&quot;)
	{?>
	<IMG NAME=&quot;campicture&quot; SRC=&quot;[URL unfurl="true"]http://www.tuck-net.com/images/AutoCapture/ispy.jpg&quot;[/URL] ALT=&quot;Picture&quot; BORDER=&quot;0&quot; HEIGHT=&quot;240&quot; WIDTH=&quot;320&quot; RELOAD=&quot;30&quot;>
		<center>Page refreshes itself every <?php print $rate; ?> seconds. Do not reload.<br>
		<table summary=&quot;&quot; align=&quot;center&quot;>
		<tr>
		<td>Number of viewers : </td><td><?php echo $viewers; ?></td>
		</tr>
		</table>
		<form action=&quot;webcam.php&quot; method=&quot;get&quot;>
		<center><input type=&quot;submit&quot; value=&quot;Start Again&quot; class=&quot;button&quot;>
		</form></center>
		<SCRIPT LANGUAGE=&quot;JavaScript&quot;>
		<!-- hide
		startClock()
		//end hide -->
		</SCRIPT>
	<?php
	}
?>
<br>
<div class=&quot;smlink&quot;><!--  <a href='javascript:close()'>Close</a> --></div>
</td>
</tr>
</table>
</center>
.:TUCK:.
 
There is no way to accurately measure the number of people hitting your site at any particular instant without analyzing in realtime the activity of your web server.

Keep in mind that the number of session files is not a count of how many people are currently viewing your webcam. It is a count of how many people have viewed your webcam in the amount of time it takes for your sessions to expire.

Also, your method will produce wildly inaccurate number if you don't have session garbage collection percentage set to 100%.


I don't know what you're putting in the variable from which you are returning count(). If you want to know how many session files there are on your filesystem, you need to take a look at PHP's Directory family of functions. Take a look at readdir() (
Want the best answers? Ask the best questions: TANSTAAFL!
 
I was afraid of that. I don't think I have access to where the session files are stored. Here's another idea: if I label the session with the same ID, will all viewers be able to access the same variable? I'm not too worried about the session timeout issue. As I see it, a new user begins viewing the webcam, this registers a variable and sets it to 1. The variable is displayed. The next user begins viewing and that increments the same varable by 1. The varable is diplayed. When viewers leave, a close button will subtract 1 from the variable. If the session times out, the variable will die too, right? .:TUCK:.
 
No such luck there, either. You're going to run into concurrency problems with that one.

You're also depending on your users' using your close script. There's no guarantee of that, either -- how many times do you log into a site and exit it by closing the browser?

Anyway, by default PHP stores its sessions in /tmp (on *nix boxes). You should have access to that. Want the best answers? Ask the best questions: TANSTAAFL!
 
I see. I tried this:
Code:
//Count sessions here
if(session_is_registered(viewers)){
	$id = &quot;count&quot;;
	session_id($id);
	session_start();
	$viewers = $viewers++;
	}
else{
	$id = &quot;count&quot;;
        $viewers = 1;
	session_id($id);
	session_start();
	session_register('viewers');
	}
I'm not too worried about people leaving. I have a link leading people to this webcam, could I use that to increment a variable? .:TUCK:.
 
True, true. If I set session.cache_expire to someting like 3 minutes, would that reset the variable after 3 minutes? .:TUCK:.
 
The best way to do what you're asking is to set up your own session handling functions that use a database to store the session data on the server.

Ironically, there's faq434-2037, written by sleipnir214 that explains how to do this. Assuming you executed the garbage collection function 100% of the time, you could just count the active sessions in the database to get a close approximation as to the number of active viewers.

If you use this, sleipnir214 should really get the credit! He's taken you this far... he even wrote the FAQ! -gerrygerry

&quot;I'm doin' a one-nighter for bitin' Ed the mail man... the guy was tryin' to cast a spell on me... like a wizard or something.&quot;
&quot;Are you sure about that?&quot;
&quot;I dunno... maybe he was just wavin' [wavey]...&quot;
 
Yeah, to zero, if your code is right.

At that rate, you might as well just write a script that randomly increments a number by a certain amount, and rezeroes the number every three minutes.

The only way it might be possible to get some kind of number that has some bearing on reality is to count the number of sessions that you have stored (again, provided your garbage collection percentage is set to 100%).

You should have access to the directory where the session files are written. You script runs as the same user as your server, and PHP can write to that directory as that user to create the session stores. You certainly should be able to count the number of files of the form &quot;sess_*&quot; in that directory. Want the best answers? Ask the best questions: TANSTAAFL!
 
create a text file; whenever anyone views the site, write &quot;epoch:ip&quot;, for example your file may look like this:

1041897600:192.168.0.1
1041897605:192.168.0.1
1041897610:192.168.0.1
1041897615:192.168.0.1
1041897620:192.168.0.1
1041897630:192.168.0.2
1041897635:192.168.0.2
1041897640:192.168.0.2
1041897650:192.168.0.2

This is a guestimate that you will be refeshing every 5 seconds or so.

Now, open the file, read it in to PHP, and delete all the records older than, say, 5 minutes, then count the number of different IPs in the file that have viewed your site.

Ref:
strtotime(&quot;now&quot;) = epoch
(strtotime(&quot;now&quot;)-(5*60)) = epoch 5 mins ago

Enjoy --BB
 
Sleipnir214 and GeryGery,

Good suggestion and good article. I don't have access to SQL on this server. Thanks for the suggestions!

BB,

That seems like a great solution. I well let you know if I go with that and the code I use. .:TUCK:.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top