Jump to content

Unique visitors to page using counter


twilitegxa

Recommended Posts

How can I alter this code to make it only count unique visits to the web page? Here is the code:

 

<?php
//Opening file to get counter value
$fp = fopen ("counter.txt", "r");
$count_number = fread ($fp, filesize ("counter.txt"));
fclose($fp);
?>
<html>
	<head>
		<title>Counter number</title>
	</head>
	<body>
	<?php
		$i="";
		$ImgPath="imgs/";	//Path of image folder
		$counter = (int)($count_number) + 1;
		$count_number = (string)($counter);
		$len = strlen($count_number);
		while($len!=$i && $len!=0)
		{
			echo "<img src=".$ImgPath.$count_number[$i].".jpg alt=\"You are visitor number $count_number\" width=20 Height=22>";
			$i++;
		}
		$fp = fopen ("counter.txt", "w");
		fwrite ($fp, $count_number);
		fclose($fp);
	?>
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/125891-unique-visitors-to-page-using-counter/
Share on other sites

How will you define a unique visitor?

 

Different IP?

  -Need to store and compare $_SERVER['REMOTE_ADDR']

 

Different browser?

  -"                  " for $_SERVER['HTTP_USER_AGENT']  <~ That can be blank, not the best to check alone..

 

Once per day?

  -  Store ip, time,.. etc

 

Once per hour?

  - same.

 

 

Most people stick with one browser... so you might md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']); and get a unique key, and store that to compare..  A database will be better than a flat file, IMO.

I do have a database in use, but I don't know how to make a counter for it. I just found this one online and decided to try it and it worked, so I used it. I didn't know there was a way to use the database to make a counter. If there is, I'd rather use it if possible I think because I want to check against unique visitors to the site, I guess by IP address maybe?

Well, depending on what you want to do, and how you want to determine unique, it could be as simple as:

 

get ip  ($_SERVER['REMOTE_ADDR'])

 

Add it to the database (if it doesn't exist already)

 

Use a SELECT COUNT(*), to see how many unique IPs you have, which can be your 'unique visitors'

 

 

Mind you, this is very simple, and not flawless..(people can get the same ip as a previous person)

So that other suggestion you said earlier,

 

Most people stick with one browser... so you might md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']); and get a unique key, and store that to compare..  A database will be better than a flat file, IMO.

 

How exactly would I do this and where would I put it? Sorry to need so much help, but I really am learning everything and don't understand how to place things sometimes. I need a walkthrough on this!

Simple Method:

-Store a hash of IP ADDRESS + USER AGENT as a unique user identifier.

Cons: Possible for user with same browser to get the same IP as a previous user (meaning, hit will already exist, and not count as a new)

However, not very likely.

 

Create a table in your database with 4 columns: uid, userhash, ipaddr, useragent

uid: INT, Auto Increment

userhash: varchar(50)

ipaddr: varchar(20)

useragent: varchar(255)

 

in your php script

<?php
$ip = $_SERVER['REMOTE_ADDR'];
$ua = $_SERVER['HTTP_USER_AGENT'];

$uhash = md5($ip.$ua);

$sql = "SELECT userhash FROM yourTable WHERE userhash='$uhash'";
$result = $db->query($sql); //query however you query
if(mysql_num_rows($result) == 0){
  $add = "INSERT INTO yourTable (userhash,ipaddr,useragent) VALUES ('$uhash','$ip','$ua')";
  $db->query($add);
}
?>

 

So basically that will add all the info if it doesn't find an existing unique hash... and you have the ip addr for reference later.

 

 

Display 'unique' vistors:

<?php
$sql = "SELECT COUNT(*) AS 'unique' FROM yourTable WHERE 1";
$result = $db->query($sql);
$row = mysql_fetch_array($result);
$visits = $row['unique'];

echo 'There have been '.$visits.' unique visitors.';
?>

 

This is a fairly longhand manner of doing things.. but it is a good basis.

I use a database object, with a method query();

 

the standard thing is:

$sql = "SELECT userhash FROM yourTable WHERE userhash='$uhash'";

$result = mysql_query($sql); //query however you query

 

mysql_query() in this case does the same as my $db->query() method

I don't know what you mean, using images how?

 

And I saw your post about the other thing (form values must equal 12), but I'm not going to answer it...  you need to determine how you will address your form.. you can always check values before actually 'saving' any form values.  But i'm not going to setup the validation for you.

I mean I was using a script that ued images in place of the numbers, but that was the one that used the txt file for the number.

 

Well, it's good to know it can be done (about the validating the form post), I just need to understand how it can be done. I don't understand how exactly to write the code for this type of validation. The code I had for my register page was:

 

$error = array();
if(isset($_POST['username'])) {
$result = @mysql_query('SELECT username FROM `users` WHERE username = \''.mysql_real_escape_string($_POST['username']).'\'');
if($row = @mysql_fetch_row($result)) {
array_push($error, 'Your username is already being used. Please select another.');
}
$len = strlen($_POST['username']);
if($len < 3 || ($len > 20)) { array_push($error, 'Your username must be between 3 and 20 characters long.'); }
$len = strlen($_POST['password']);
if($len < 6 || ($len > 20)) { array_push($error, 'Your password must be between 6 and 20 characters long.'); }
$len = strlen($_POST['name']);
if($len > 100) { array_push($error, 'Sorry, your name can be no longer than 100 characters long.'); }
if(!$_POST['name']) { array_push($error, 'You must provide your name'); }
if(preg_match('/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i', $_POST['email']) == false) {
array_push($error, 'Your e-mail address is incorrect');
}
$len = strlen($_POST['email']);
if($len > 255) { array_push($error, 'Sorry, your e-mail address is too long.'); }
if(!$error) {
@mysql_query('INSERT INTO `users` (username, password, name, email) VALUES (\''.mysql_real_escape_string($_POST['username']).'\', \''.mysql_real_escape_string(md5($_POST['password'])).'\', \''.mysql_real_escape_string($_POST['name']).'\', \''.mysql_real_escape_string($_POST['email']).'\')');
header('Location: login.php');
die('<a href="login.php">Login</a>');
}
}

 

But since the page is the same page that sends the data into the table, I was unsure what I would do. I'm guessing I could alter my code to say something like:

 

$error = array();

if($_POST['body'] + $_POST['mind'] + $_POST['mind'] == 12)

 

if(!$error) {

header('Location: nextpage.php');

 

I know you said you aren't going to write the code out for me, but will you tell me if I'm heading in the right direction? Because as I said on one of my posts, I am putting these pages into a session, so they values from be submitted until several pages later anyway and will rather be pulled along from page to page untilt they are inserted on the final page.

 

Also, I'm assuming I would put my validation code before the form, is that right? I'm assuming it has to at least be before the submit button, but would it work if it were before the form itself, or is there a better place to put it? I think my above code is incorrect, but I'm not that good with if/else statement yet. Am I close even?

Images for numbers?  You can do w/e you want, the code I gave you returns a number.. just as your text file should have..

 

form validation...

 

user enters values

form posts (to self, or another page)

 

do your validations... you have it right, "if no errors, insert into database", otherwise, show the form again

In your validations, you can add the "if($_POST['body'] + $_POST['mind'] + $_POST['mind'] == 12)", and throw an error if not

 

As for storing it in a session, that's your choice, I don't know what to tell you... you're doing it in a 'right way', depending on your situation.  just see it through, and see what works and what doesn't.

 

Also, use $error[] = 'message', instead of array_push($error,'message')// it's faster

 

I can suggest this though:

 

<?php
if(isset($_POST['field1'])){ // usually I have it check to see if an important field is set before attempting to process
  if(strlen($_POST['field']) < 25 || strlen($_POST['field']) > 25){
    $errors[] = 'Field 1 needs to be btwn 3-25 chars';
  }

  if(intval($_POST['field2']) != 12){
    $errors[] = 'Field 2 is not equal to 12';
  }

  if(!$error){
    $field1 = mysql_real_escape_string($_POST['field1']);
    $field2 = mysql_real_escape_string($_POST['field2']);
    
    mysql_query('INSERT INTO `yourtable` (col1,col2) VALUES ('$field1','$field2');
    header('Location: completed.php'); // form was success, go somewhere else
  }
}

if($error){
  $e = count($error);
for($i=0;$i<$e;$i++){
  echo $error[$i].'<br />';//display errors if any
}
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
  One<input type="text" name="field1" /><br />
  Two<input type="text" name="field2" /><br />
</form>

 

Something like that is a working structure.

I tried altering your examplefor my form and this is what I came up with (tell me what I'm doing wrong):

 

<?php
if(isset($_POST['total'])){ 

  if(intval($_POST['total']) != 12){
    $errors[] = 'Total is not equal to 12';
  }

  if(!$error){
    $body = mysql_real_escape_string($_POST['body']);
$mind = mysql_real_escape_string($_POST['mind']);
$soul = mysql_real_escape_string($_POST['soul']);
    
    mysql_query('INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul');
    header('Location: scout.php'); // form was success, go somewhere else
  }
}

if($error){
  $e = count($error);
for($i=0;$i<$e;$i++){
  echo $error[$i].'<br />;//display errors if any
}
}
?>

 

I'm receiving this error:

 

Parse error: syntax error, unexpected T_VARIABLE in C:\wamp\www\files\assignstats.php on line 106

 

And line 106 is the line that says:

 

<?php
mysql_query('INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul');
?>

 

I tried adding this to it ') at the end:

 

<?php
mysql_query('INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul')');
?>

 

But that didn't fix it. What else am I missing or doing wrong?

If I were you, I'd setup your query separately, then query the variable, like this:

 

<?php
$sql = "INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul')";// YOU WERE MISSING A ' at the END, before the )
  mysql_query($sql);
?>

If I take out the line with the query:

 

mysql_query('INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul');

 

Don't I also need to move the line with the header? The code would be like this, I'm guessing:

 

<?php
$sql = "INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul'
  mysql_query($sql);
header("Location: scout.php");

 

But I still have some kind of error:

 

Parse error: syntax error, unexpected T_VARIABLE, expecting ',' or ';' in C:\wamp\www\files\assignstats.php on line 118

 

 

$sql = "INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul')";

 

What is still missing or incorrect?

?>

Try this, it's your original code with fixes:

Compare this to what you had, you were missing several simple errors...

You were missing a ' at the end of $soul in your query....,'$soul')

You were missing a ' at the end of $error[$i].'< br />'.  (no space btwn < and br>)

<?php
if(isset($_POST['total'])){ 

  if(intval($_POST['total']) != 12){
    $errors[] = 'Total is not equal to 12';
  }

  if(!$error){
    $body = mysql_real_escape_string($_POST['body']);
$mind = mysql_real_escape_string($_POST['mind']);
$soul = mysql_real_escape_string($_POST['soul']);
    
    mysql_query("INSERT INTO `stats` (body,mind,soul) VALUES ('$body','$mind','$soul')");
    header('Location: scout.php'); // form was success, go somewhere else
  }
}

if($error){
  $e = count($error);
  for($i=0;$i<$e;$i++){
    echo $error[$i].'<br />';//display errors if any
  }
}
?>

With this code, it give this error, but still displays the page:

 

Warning: Cannot modify header information - headers already sent by (output started at C:\wamp\www\files\menu.php:75) in C:\wamp\www\files\assignstats.php on line 104

 

But I don't see any header information in my menu.php file. Here is the code for menu.php:

 

<html>
<head>
<!-- Source File -->
<link rel="stylesheet" type="text/css" href="ddlevelsfiles/ddlevelsmenu-base.css" />

<link rel="stylesheet" type="text/css" href="ddlevelsfiles/ddlevelsmenu-sidebar.css" />

<script type="text/javascript" src="ddlevelsfiles/ddlevelsmenu.js">
</script>
<link rel="stylesheet" type="text/css" href="main.css" />
<!--[if IE]>
<style>
#main
{
padding: 20px 0 20px 0;
}

</style>
<![endif]-->
</head>
<body><table align="center"><tr><td>
<center><img src="logo.png" alt="Sailor Moon RPG Logo" title="Sailor Moon RPG Logo" /></center></td><td valign=bottom>
<?php echo "Unique Visitors";
include("counter.php"); ?></td></tr></table>
<div id="head">
<address><a href="seestore.php" title="Item Store">Item Store</a> | <a href="register.php" title="Register">Register</a> | <a href="youraccount.php" title="Your Account">Your Account</a> | <a href="help.php" title="Help">Help</a>
</address></div>
<table align="right">
<tr>
<td><?php
if ($_SESSION['loggedIn'] == 1) {
?>
<p>Welcome, <?php echo $_SESSION['userName'] ?> (<a href="login.php?action=logoff" title="Log Out">Log out</a>)</p>
<?php
} else {
?>
<p>Please <a href="login.php" title="Log In">log in</a></p>
<?php } ?>
</td>
</tr>
</table><br />
<div id="ddsidemenubar" class="markermenu">
<ul>
<li><a href="home.php" title="Home Page">Home</a></li>
<li><a href="#" title="Getting Started" rel="ddsubmenuside1">Getting Started</a></li>
<li><a href="creationform.php" title="Create Character">Create Character</a></li>
<li><a href="#" rel="ddsubmenuside2" title="Members">Members</a></li>
<li><a href="newsandevents.php" title="News And Events">News And Events</a></li>
<li><a href="glossary.php" title="Glossary">Glossary</a></li>
<li><a href="topiclist2.php" title="Battle Board">Battle Board</a></li>
<li><a href="chatframe.php" title="Battle Chat Lounge">Battle Chat Lounge</a></li>
<li><a href="about.php" title="About Us">About Us</a></li>
<li><a href="news.php" title="Newsletters">Newsletters</a></li>
<li><a href="invite.php" title="Invite Friends">Invite Friends</a></li>
<li><a href="topiclist.php" title="Discussion Board Forum">Discussion Board</a></li>
<li><a href="faq.php" title="Frequently Asked Questions">FAQ</a></li>
<li><a href="contact.php" title="Contact Us">Contact Us</a></li>
</ul>
</div>

<script type="text/javascript">
ddlevelsmenu.setup("ddsidemenubar", "sidebar") //ddlevelsmenu.setup("mainmenuid", "topbar|sidebar")
</script>

<!--HTML for the Drop Down Menus associated with Side Menu Bar-->
<!--They should be inserted OUTSIDE any element other than the BODY tag itself-->
<!--A good location would be the end of the page (right above "</BODY>")-->


<!--Side Drop Down Menu 1 HTML-->

<ul id="ddsubmenuside1" class="ddsubmenustyle blackwhite">
<li><a href="#" title="Chapter 1: Introduction" rel="ddsubmenuside3">Chapter 1: Introduction</a>

<ul class="smaller2"><li><a href="genre.php" title="The Magical Girl Genre">The Magical Girl Genre</a></li><li><a href="sailormoon.php" title="Bishojo Senshi Sailormoon"><em>Bishojo Senshi Sailormoon</em></a><li><a href="seriesbackground.php" title="Sailor Moon Series Background">Sailor Moon Series Background</a><ul class="smaller3"><li><a href="summary1.php" title="Season One Summary (Episodes #1 - #40)">Season One Summary</a></li><li><a href="summary2.php" title="Season Two Summary (Episodes #41 - #82)">Season Two Summary</a></li></ul></li><li><a href="roleplaying.php" title="What Is Role-Playing?">What Is Role-Playing?</a></li><li><a href="example.php" title="An Example Of Play">An Example Of Play</a></li><li><a href="size.php" title="Character Size Relationship">Character Size Relationship</a></li></ul></li>
<li><a href="creation.php" title="Chapter 2: Character Creation">Chapter 2: Character Creation</a>
<ul class="smaller4"><li><a href="creationflowchart.php" title="Character Creation Flowchart">Character Creation Flowchart</a></li><li><a href="gmdiscussion.php" title="GM Discussion">Step 1: GM Discussion</a></li><li><a href="outline.php" title="Character Outline">Step 2: Character Outline</a></li><li><a href="stats.php" title="Assign Stats">Step 3: Assign Stats</a></li><li><a href="attributes1.php" title="Character Attributes">Step 4: Character Attributes</a><ul><li><a href="attributes2.php" title="Scout/Knight Sub-Attributes">Scout/Knight Sub-Attributes</a></li><li><a href="attributes3.php" title="Negaverse/Dark Sub-Attributes">Negaverse/Dark Sub-Attributes</a></li><li><a href="attributes4.php" title="Neutral Attributes">Neutral Attributes</a></li></ul></li><li><a href="defects.php" title="Character Defects">Step 5: Character Defects</a></li><li><a href="derived.php" title="Derived Values">Step 6: Derived Values</a><ul class="smaller5"><li><a href="derived.php#combat" title="Combat Value">Combat Value</a></li><li><a href="derived.php#health" title="Health Points">Health Points</a></li><li><a href="derived.php#energy" title="Energy Points">Energy Points</a></li></ul></li><li><a href="background.php" title="Background Points">Step 7: Background Points</a></li></ul></li>
<li><a href="#" title="Chapter 3: Game Mechanics">Chapter 3: Game Mechanics</a>
<ul class="smaller6"><li><a href="introduction.php" title="Introduction">Introduction</a></li>
<li><a title="Combat Flowchart">Combat Flowchart</a></li>
<li><a href="dice.php" title="Dice, Stat Checks, & Combat Rolls">Dice, Stat Checks, & Combat Rolls</a><ul class="smaller7"><li><a href="dice.php#stat" title="Stat Checks">Stat Checks</a></li><li><a href="dice.php#combat" title="Combat Dice Rolls">Combat Dice Rolls</a></li></ul></li>
<li><a href="action.php" title="Taking Action">Taking Action</a></li>
<li><a href="combat.php" title="Combat">Combat</a><ul class="smaller8"><li><a href="combat.php#initiative" title="Initiative">Initiative</a></li><li><a href="combat.php#attack" title="Attack">Attack</a></li><li><a href="combat.php#noncombat" title="Non-Combat Actions">Non-Combat Actions</a></li><li><a href="combat.php#defend" title="Defend">Defend</a></li><li><a href="combat.php#damage" title="Deliver Damage">Deliver Damage</a></li></ul></li>
<li><a href="weapons.php" title="Weapons And Armor">Weapons And Armor</a></li>
<li><a href="recovering.php" title="Recovering Lost Points">Recovering Lost Points</a>
<ul class="smaller9"><li><a href="recovering.php#health" title="Health Points">Health Points</a></li>
<li><a href="recovering.php#energy" title="Energy Points">Energy Points</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="universe.php" title="Role-Playing In A Sailor Moon Universe">Chapter 4: RPing In A SM Universe</a>
<ul class="smaller10"><li><a href="japan.php" title="Japan And Tokyo">Japan And Tokyo</a></li>
<li><a href="#" title="Maps Of Japan And Tokyo">Maps Of Japan and Tokyo</a></li>
<li><a href="places.php" title="Places In Sailor Moon">Places In Sailor Moon</a></li>
<li><a href="timeline.php" title="Sailor Moon Timeline">Sailor Moon Timeline</a></li>
<li><a href="kingdom.php" title="The Moon Kingdom">The Moon Kingdom</a>
<ul class="smaller11"><li><a href="kingdom.php#light" title="The Kingdom Of Light">The Kingdom Of Light</a></li>
<li><a href="kingdom.php#members" title="Members Of The Royal Court">Members Of The Royal Court</a></li>
<li><a href="kingdom.php#planetary" title="The Planetary Kingdoms">The Planetary Kingdoms</a></li>
</ul>
</li>
<li><a href="negaverse.php" title="The Negaverse">The Negaverse</a>
<ul class="smaller12"><li><a href="negaverse.php#known" title="What Is Known">What Is Known</a></li>
<li><a href="negaverse.php#unknown" title="Speculation On What Is Unknown">Speculation On Unknown</a></li>
</ul>
</li>
<li><a href="makaiju.php" title="Planet Of Makaiju">Planet Of Makaiju</a>
<ul class="smaller13"><li><a href="makaiju.php#campaign" title="Campaign And Setting Questions">Campaign & Setting Questions</a></li></ul>
</li>
<li><a  href="crystal.php" title="Crystal Tokyo">Crystal Tokyo</a>
<ul><li><a href="crystal.php#campaign" title="A Crystal Tokyo Campaign">A Crystal Tokyo Campaign</a></li></ul>
</li>
<li><a href="nemesis.php" title="Nemesis, The Dark Moon">Nemesis, The Dark Moon</a></li>
<li><a href="life.php" title="School Life In Japan">School Life In Japan</a></li>
<li><a href="advice.php" title="Advice For The Player">Advice For The Player</a></li>
</ul>
</li>
</ul>

<!--Side Drop Down Menu 2 HTML-->

<ul id="ddsubmenuside2" class="ddsubmenustyle blackwhite smaller1">
<li><a href="heroes.php" title="Heroes">Heroes</a></li>
<li><a href="villains.php" title="Villains">Villains</a></li>
</ul>
</code]

This menu.php is included on every page. It's my navigation links and logo at the top of the page, includig my session log in. What am I missing now?

It means that assignstats.php has echoed something to the screen, making it so that menu.php cannot modify header info or w.e

 

The issue is that somewhere before a header('Location: ...') call, something has been output to the browser, so it cannot actually use the header command anymore.  Find out what's outputting before your header call.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.