PHP - consecutive page visits - php

my question is simple : How can I count how many consecutive days visitor have visited my site (php), any ideas are welcome.

Simple:
Just have some concept of either logging in, or a persistent cookie (logging in is more reliable since they can clear cookies). Then in your database have a field for "last logged in". If the last logged in field matches yesterday's date, increment your consecutive visit count, otherwise reset it.
EDIT: it's probably obvious, but make sure you update the "last logged in" field after you check it to be today, otherwise every time they load the page it'll increment the count!
EDIT: a quick example may look something like this (psuedo code):
// first you need to set $last seen from the DB..
// first you need to set consecutive from the DB too..
// once you have, you can do something like this.
if(strtotime('-1 day', date('Y-m-d')) == $last_seen) {
$consecutive = $consecutive + 1;
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=%d WHERE id=%d', $consecutive + 1, $id));
} else if(date('Y-m-d') == $last_seen) {
// ok, they logged in today again, do nothing.
} else {
$consecutive = 0; // only really needed if you plan on displaying it to the user
// later in this script
mysql_query(sprintf('UPDATE user SET last_seen=NOW(),consecutive=0 WHERE id=%d',$id));
}

cookies
if(isset($_COOKIE["identifier"])){
// log as existing user
}else{
setcookie('identifier', $id_value, ...
}
It wont work if people clear there cookies, which is why they clear cookies.

You can use pluggable traffic analitic tools, commercial or less like Google Analitics.

Related

Destroy session in PHP

Hi guys I am working on a program which will execute the number of people visit a website and when the date changes it will start from 0. So I have nearly figure out how to do it but it doesn't appear as 0 when the date changes here is my code:
<?php
session_start();
?>
<?php
if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;
else
$_SESSION['views']=1;
echo "You are the ". $_SESSION['views'] ." Visitor";
?>
As #Zwirbelbart said, don't use sessions for solving this. Use a DB, or at least a file, where you'll store the number of visitors.
Something like this:
function incrementVisitorsCount() {
$currentDay=date("Ymd");
if(!isset$_SESSION["visited"] || $_SESSION["visited"] != $currentDay) {
incrementYourDailyCounter($currentDay);
$_SESSION["visited"]=$currentDay;
}
}
incrementYourDailyCounter being the function that will increment the relevant value in the storage you chose (I would suggest a table in a DB you're most certainly already using).
You can base your counter on IP instead of sessions, but it means that you keep a record of each IP that visited your website each day.

How to prevent users to open same page more than once at a time

On my website people earn points by seeing a page. They get 1 point for each second they keep the page open (the page keeps rotating Advertisements).
Some people have started exploiting this by opening that page multiple times all together and hence are earning more points! for example if the user open the page 10 times then he is earning 10 points for each second. I don't want them to earn more than 1 point per second.
How can I prevent the users from opening that page more than once at the same time?
Thanks in advance.
note : My website is php based.
I have on easy but not reliable way in mind:
Set a Sessionvar like
$_SESSION['user_already_on_page'] = true;
Now you can check for this variable and return an error page or something like that.
if($_SESSION['user_already_on_page'])
{
//maybe the user has left unexpected. to workaround this we have to check
//for the last db entry. Examplecode:
$query = mysql_query($_db,'SELECT LastUpdated FROM Pointstable WHERE U_Id = $uid');
$row = mysql_fetch_array($query);
if((time()-$row['LastUpdated']) < 5)
{
die("You are already on this page!");
}
//$_SESSION['user_already_on_page'] is set but the last update is older than 5 sec
//it seems, that he unexpectedly lost connection or something like that.
}
To unset this variable you could fire an AJAX-Script on pageclose that unsets this variable.
So your unsetonpage.ajax.php could look like this:
<?php $_SESSION['user_already_on_page'] = false;?>
And your JS-Part (using jquery):
$(window).bind('beforeunload', function(eventObject) {
$.ajax({url:'./ajax/unsetonpage.ajax.php',type:'GET'});
});
This should work.
Add the time when the page is opened to the database. Whenever the page is opened check if the difference b/w that time and current time is less than xx seconds then redirect the user. If the difference is more than xx seconds then update that time.
//--- You make session in startup called (my_form)
if (!empty($_SESSION['my_form']))
{
if ($_SESSION['my_form']== basename($_SERVER['PHP_SELF']))
{
header("Location:index.php");
exit();
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}
} else {
$_SESSION['my_form']= basename($_SERVER['PHP_SELF']);
}

Form loop with password cracking

I have a somewhat hack-ish question and I'm intrigued as to how I would do the following (if even possible):
Basically, to give a bit of context, I had an account on a site a few years ago and had a username and password for the portal to log in and see all my information/transcript/etc. I haven't connected since I stopped using it a couple years ago by I wanted to view the information that I submitted. Problem is, I can no longer remember the password (to a certain degree). And if I go the 'forgot password' route, it's linked to a really old hotmail address which was deactivated a while back.
I'm aware that this will involve some sort of password crack and I don't want to talk about ways to screw people and gain access to their accounts but it's mine and I'm curious if this is possible.
Thing is, I have the username and I have the majority of the password, all except the final 2 numbers. I can't remember them. I know I added 2 digits at the end because I was forced to (between 10 and 99).
So say my username was 'johnsmith' and my password was 'eatdog##', is there a way to create a form and loop it over and over until the password is guessed correctly? I'm aware they might have some sort of protection against the amount of tries per 'whatever amount of time'.
Thanks.
Considering you only need to iterate over < 100 different possibilities, this should be crackable.
View the HTML source of the page that contains the login form and see which page the form submits to. Lets assume it is action.php. You will see something like this in the HTML source:
<form id="login" action="action.php" method="post">
Use cURL to make a POST request to action.php with your username and password as POST parameters (including anything else the form is posting). Do this in a loop with the password changing at each iteration.
Your code should look something like this (in PHP)
$username = "johnsmith";
$pass_base = "eatdog";
$url = "the url the form submits to";
$failed = ""; //the response returned by the server when login fails
for ($i=10; $i < 100; $i++)
{
$password = $pass_base . $i;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
//set the POST parameters
$data = curl_exec($ch);
curl_close($ch);
if ($data != $failed) //analyze the returned data
{
echo $password; //this is your password
break;
}
}
The above code is a PHP script. It WILL NOT run as is. I've only provided the meat of the script. You might have to do some basic initialization - hopefully you're somewhat familiar with PHP.
You can run it from your localhost (install WAMP). I'd estimate it shouldn't take more than 5 min to run through all the passwords.
This would only work if the login process isn't specifically designed to stop brute force attacks. If it locks you out for x min after y unsuccessful logins, you'd have to sleep the PHP script after every y-1 attempts for sometime so as not to trigger the lockout.
If it starts asking for captcha, the above script won't work.
If they didn't add mysql_real_escape_string then you can force your way in by entering your username and for your password enter a blank space followed by
" OR 1=1
The double quotes will set the password slot equal to nothing. The or will force the mysql query to check the second statement should password not return the proper value, it won't.
And thus 1 always equals 1 and you will be allowed to log-in.
You'd think most websites would use the simple function so it might not work but it's worth one login attempt.
If you were the owner of the site and you wanted to do something about this, a really rough way to defend against this would be something like (using PHP):
$count = file_get_contents('/some/writable/dir/'$_POST['username']);
if (!$count) {
$count = 0;
}
if ($count > 5) {
print "Naughty!"; // or add a CAPTCHA or something
exit;
}
$success = checkLogin($_POST['username'], $_POST['password']);
if ($success) {
// set cookies, send them away with header('location:blah.php'); exit
} else {
$count ++;
file_put_contents('/some/writable/dir/'$_POST['username'], $count);
}
And set a cron job to delete all the files in /some/writable/dir/ every five minutes or so.
Like I said, it's properly rough, but it should give you an idea of how to start adding some armour to your site.

If statement, sessions variables

The following code is within an ajax call. I'm trying to make sure people don't vote on questions with a certain id too often using sessions.
So they click a button, which executes the following php code:
$id=$_GET["id"];
if ((isset($_SESSION["$id"]) && ((time() - $_SESSION["$id"]) > 180)) || (!isset($_SESSION["$id"]))) {
// last vote was more than 3 minutes ago
$_SESSION["$id"] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
So I'm creating a session variable for each question id which holds the time() of their last vote. I would do this with cookies, but they can be disabled.
Currently, there is a bug somewhere with my logic, because it allows the user to keep clicking the button and adding as many votes as they want.
Can anyone see an error that I have made?
using sessions to prevent multiple voting makes very little sense.
sessions do use cookies with the same drawbacks
unlike strings, variables in PHP should be addressed without quotes. such a false usage WILL cause an error someday.
I see no point in checking for isset($_SESSION[$id]) twice.
There was a bug in PHP which disallowed numerical indices for the $_SESSION array. Dunno if it was corrected nowadays.
As it was pointed out by Sajid, you have to call session_start() before using $_SESSION array.
now to the logic.
to me, it seems the code won't let anyone to vote at all. as it won't pass isset($_SESSION[$id]) condition for the first time and won't let $_SESSION[$id] to be set and so on.
it seems correct condition would be
if ( (!isset($_SESSION['vote'][$id]) OR (time() - $_SESSION['vote'][$id]) > 180) )
You need to call session_start() to start the session before any headers are sent. Otherwise, sessions will not be enabled unless the ini setting to autostart sessions is on. Also, your server must be correctly configured to be able to store session files (usually a writable tmp dir is needed). See more about sessions here: http://www.php.net/manual/en/ref.session.php
There might be a problem with the if statement. Try the following
$id=$_GET["id"];
if (((isset($_SESSION[$id]) && ((time() - $_SESSION[$id]) > 180))) || (!isset($_SESSION[$id]))) {
// last vote was more than 3 minutes ago
$_SESSION[$id] = time(); // update/create vote time stamp
//there is code here to add the vote to the database
}
else{
echo "sorry, you've already voted recently";
}
Perhaps time() returns milliseconds and you should compare to 180000 instead of 180.

Display Ads To % of Users

I have a site that I want to display ads to 10% of my traffic. I am getting on average around 30,000 hits a day and want 10% of those users to see an ad from one of my advertisers.
What's the best way to go about implementing this?
I was thinking about counting the visitors in a database, and then every 10 people that visit 1 user gets an ad. Or is there a better way of going about it?
I'm no good with math, so I'm not sure what's the best approach.
Generate a random number between 1 and 10, and compare it to a fixed number, and your code will run on average 10% of the time:
if (rand(1,10) == 1) {
echo 'ad code';
}
You can make this per-user instead of per-pageview by storing whether that user was 'chosen' in their session.
session_start();
if (isset($_SESSION['show_me_ads']) || rand(1,10) == 1)
$_SESSION['show_me_ads'] = true;
echo 'ad code';
}
I use Google's DFP (Doubleclick for Publishers) to serve ads on my site. It's pretty robust. You have to have an AdSense account, but that's not very hard to obtain, it's just annoying to wait to be approved.
Once you have it set up and your ads loaded in, you can control how many people see your ad by percentage (such as the 10% you were talking about), total pageviews, etc.
Look into it: http://google.com/dfp
If you'd rather not use 3rd party software, I'd think the simplest way would be to randomize it so 1/10 visitors see your ad. The simple way would be:
if (rand(1,10) == 1) {
echo 'YOUR AD CODE HERE';
}
You said you're not good at math, and I understand that, I'm pretty horrible at it too, but basically, every time the page is loaded, it's "rolling" a 10-sided "dice". Every time it "rolls" a 1 (which would be 1 out of 10 times, or 10%), it'll display the ad. Otherwise, it'll be ignored.
The reason this is better than relying on counting the number of users (aside from simplicity) is that it will still roll 1 10% of the time whether you have 30,000 visitors or 3,000,000.
In its simplest form:
if (rand(1,10) == 1) {
echo $ad_content;
}
if(rand ( 1,10) == 1)
display_ads();
You can use
if(mt_rand(1,10)==10){
//show your code;
}
It will show ads to about 10% users
Why would you show ads to a few unlucky ones instead of randomly deciding per page impression (instead of per visitor)?
In php, you can just go ahead and write:
$adPercent = 10;
if (rand(0, 100) < $adPercent) {
echo '<div class="ads">Buy now!</div>';
}
if this was for google ads, then you would need to make the ad insertion optional (using the prob logic above), suggest something along the lines of Google Ads Async (asynchronous)
<script type="text/javascript"><!--
// dynamically Load Ads out-of-band
setTimeout((function ()
{
// placeholder for ads
var eleAds = document.createElement("ads");
// dynamic script element
var eleScript = document.createElement("script");
// remember the implementation of document.write function
w = document.write;
// override and replace with our version
document.write = (function(params)
{
// replace our placeholder with real ads
eleAds.innerHTML = params;
// put the old implementation back in place
document.write=w;
});
// setup the ads script element
eleScript.setAttribute("type", "text/javascript");
eleScript.setAttribute("src", "http://pagead2.googlesyndication.com/pagead/show_ads.js");
// add the two elements, causing the ads script to run
document.body.appendChild(eleAds);
document.body.appendChild(eleScript);
}), 1);
//-->
</script>

Categories