PHP Session custom class sessions not being set? - php

I have a custom class I am writing for easier scripting for myself. I generate life spanned sessions and normal sessions (normal life span). So here's my script parts for creating and getting
CREATE
public static function create($session_name,$value="") {
//check if the $_SESSION was started manually without using our functions...
if(!isset($_SESSION)) {
//init this- it creates session_start session_id
self::init(self::$settings["default_name"]);
}
//create array for serialization
$new_session = array();
//if our session is an array means we want this session to have some unique properties compared to others
if( is_array($session_name)) {
//store the session value in the array
$new_session["value"] = $session_name["value"];
//total time is null, this indicates if we want a life expectancy of total 10 hours total or total from current time.
$total = null;
if(isset($session_name["lifeclock"])) { //lifeclock should be a hh:mm:ss format to be exploded
$clock = explode(":",$session_name["lifeclock"]); //we've exploded it now assign it
$hours = $clock[0]; //hours
$minutes = $clock[1]; //minutes
$seconds = $clock[2]; //seconds
$session_add = 0; //variable to be added to total or not technically
if(isset($session_name["concurrent"])) {
$session_add = time(); //if concurrent time is true assign time to the session_add
}
$total = ( $session_add ) + ((int)$hours * 60 * 60) + ((int)$minutes * 60) + (int)$seconds; //broken down math to make all seconds
}
if(!isset($total)) { //this is why total is null
$total = self::$settings["lifetime"]; //if null lifetime we'll use the default lifetime
}
session_set_cookie_params( $total, //assing all data to the session_set_cookie_params
isset($session_name["path"]) ? $session_name["path"] : self::$settings["path"],
isset($session_name["domain"]) ? $session_name["domain"] : self::$settings["domain"],
isset($session_name["secure"]) ? $session_name["secure"] : self::$settings["secure"],
isset($session_name["httponly"]) ? $session_name["httponly"] : self::$settings["httponly"]
);
$new_session["life"] = $total; //we'll also add the time and when it was born
$new_session["born"] = time(); // so the user can use this later in the programming code
$_SESSION[$session_name["name"]] = serialize($new_session); //serialize the array
} elseif(is_string($session_name)) {
$new_session["value"] = $value; //assign value value
$new_session["born"] = time(); //assign born time
$_SESSION[$session_name] = serialize($new_session); //serialize the array
}
session_write_close(); //close the lock
}
GET
public static function get($session_name,$data = false) {
//test if session has been opened via manual or programatically
if(!isset($_SESSION)) {
self::init(self::$settings["default_name"]);
}
//if data argument is true meaning we don't want all the extra information we'll just return value!
if($data === false) {
if(isset($_SESSION[$session_name])) {
$sess = unserialize($_SESSION[$session_name]);
if(isset($sess["value"])){
return $sess["value"];
} else return false;
} else return false;
} elseif($data === true) {
return unserialize($_SESSION[$session_name]);
}
}
Now here is my file for testing this altogether.
<?php
set_include_path(dirname($_SERVER["DOCUMENT_ROOT"]));
require "admininit__autoload.php";
Session::configure(array(
"default_name"=>"boogie",
"lifetime"=> 3600,
));
Session::create( array(
"name"=>"my_session",
"value"=>"boogie all night long",
"lifeclock"=>"00:05:00"
));
$session_value = Session::get("my_session");
var_dump($session_value);
echo "<pre>";
print_r($_SESSION);
echo "</pre>";
?>
So this is what I get in response to the var_dump and print_r
bool(false)
Array
(
)
So this tells me that $session_value is return false from the get function meaning altogether that the darn session is not saving for some strange reason. Here is what I see in google developers resource panel as well
So to me that's telling me a session is being created somewhere. I've also went ahead and checked my /tmp folder and see no file starting with sess_ which is the usual file for sessions. Any hints as to where my issue lies or maybe flat out what the hell is wrong here?
Update
While the creation of the code is uncommented out I get this
array(1) {
["my_session"]=> string(88) "a:3:{s:5:"value";s:21:"boogie all night long";s:4:"life";i:300;s:4:"born";i:1431562088;}"
}
string(21) "boogie all night long"
Array
(
[my_session] => a:3:{s:5:"value";s:21:"boogie all night long";s:4:"life";i:300;s:4:"born";i:1431562088;}
)
But when I comment out the creation part it returns this
bool(false)
Array
(
)

Related

Return different user name every 30 minutes PHP

Im trying to implement a solution for database user limit exceed problem by using a different database user every 3 minutes.
I created 4 users and the script works fine with 3 users but at the forth one, it returns the first username again and keep returning it a while.
<?php
function GetUser()
{
$file = $_SERVER['DOCUMENT_ROOT'] .'/dbUsers.txt';
$users = array("user1", "user2", "user3","user4");
$user = "";
$userIndex = 0;
if (file_exists($file)) {
if (filemtime($file) < time()-100) //0.5*3600
{
$userIndex = file_get_contents($file);
if($userIndex >4)
$userIndex =0;
file_put_contents($file, $userIndex + 1);
}
}
else
{
file_put_contents($file, $userIndex);
}
$user = $users[$userIndex];
return $user;
}
?>
Thanks in advance.
Why using a file and file time. You said "every 30 minutes"
function GetUser()
{
# static: define once on scan/compile time
static $users = array("user1","user2","user3","user4");
$index = intval( time() / (30*60) ) % count($users);
return $users[$index];
}
Notes: time() returns the number of seconds since epoch (1971-01-01 0:00:00 UTC). Then I divided it by 30 minutes (30*60). The modulo operator % iterates through the user list.

Why is my session not working when I try to count IP hits?

I'm trying to create a counter in PHP that will count how many times within a set timeframe an IP can visit a page and when it hits a download counter within that timeframe it re-directs. The approach I've seen recommended was doing this with a session after referencing several Q&As:
PHP function to increment variable by 1 each time
How to not increase page/post view count with refresh?
php increment variable value with 1 when submit
I also looked at:
How do I count unique visitors to my site?
adding counter to php page to count the unique visitors
I do not have much experience with cookies and sessions so I believe that is where I fault in my code. If you have any suggestions on better implementation than what I am doing please advise.
The code:
$jsonFile = 'foobar.json';
$theJSON = file_get_contents($jsonFile);
$jsonArray = json_decode($theJSON, true);
$theIP = "123.123.123"; // $_SERVER['REMOTE_ADDR']
$thisTime = date("H:i");
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = date("H:i", strtotime($thisTime)+(($addMin*60)+($addHour*60*60)));
if (!empty($theIP) && !empty($jsonArray)) {
foreach ($jsonArray as $value) {
if (in_array($theIP, $value, true)) {
echo "yes"; // header('Location: https://www.url/darthvader.com');
exit();
} else {
if ($thisTime <= $timeLater) { // where my issue starts
echo $timeLater; // for testing
session_start();
$counter = $_SESSION['promo_number'];
$counter++;
if ($counter == $downloadHits && file_exists($jsonFile)) {
$currentData = file_get_contents($jsonFile);
$currentArray = json_decode($currentData, true);
$theStuff = array(
'ip' => "123.123.123", // $_SERVER['REMOTE_ADDR']
'date' => date("H:i"),
'time' => date("m.d.y")
);
$currentData[] = $theStuff;
$finishData = json_encode($currentData);
} else {
echo 'bar'; // for testing
session_unset();
session_destroy();
}
}
}
}
} else {
echo '<span style="color:red; font-weight:bold;">empty file</span>';
}
What I am trying to do is count the times an IP visits a post within a set time and if it hits that count redirect the IP. I do know that the IP can be spoofed and I am not worried about that plus I would prefer to not use a database at this time. So how can I properly set a session to count the hits and if the IP hits the post in set count it redirects the IP?
EDIT:
After doing some reading and the help from the comment and answer I've made an edit that I hope explains what I am trying to do. After researching further I ran across:
session_destroy() after certain amount of time in PHP
How do I expire a PHP session after 30 minutes?
which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 2; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 1; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
$_SESSION['expire'] = $timeLater;
if (!empty($theIP) && !empty($jsonArray)) {
//look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
echo 'IP found in json';
exit;
}
// look at the time the session was set, add to counter or delete session
if ($_SESSION['count'] = isset($_SESSION['count']) && time() < $_SESSION['expire'] ) {
echo 'adding to count';
$_SESSION['count'] + 1;
// limit reached. Add IP to blacklist
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max';
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
session_destroy();
} else {
echo 'setting count to 1';
$_SESSION['count'] = 1;
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
But sadly now the $_SESSION['count'] + 1; no longer increments.
Darth_Vader you're almost there. There are a couple of issues with your script.
You never save the count in session, so you have no way to retrieve it later
You start your session late in the script. This is poor practice because it will break as soon as you echo something higher up or forget and try to use $_SESSION higher up
You read your JSON file and decode it twice unnecessarily, wasting system memory
You never save the changes you make to the JSON
You call session_unset() and session_destroy() after a successful download, so the count would be lost even if you were trying to save it properly
My modifications:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$thisTime = time();
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$downloadHits = 5; // set value for testing purposes
$timeLater = $thisTime + ($addMin*60) + ($addHour*60*60);
if(empty($theIP)){
echo 'empty file';
exit;
}
//look for the $theIP in the 'ip' column
if(in_array($theIP,array_column($jsonArray,'ip'))){
echo 'IP found in json';
exit;
}
if($thisTime > $timeLater){//not sure what you want to do here
exit;
}
//increment the count, or set it to 1 to begin
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count']+1 : 1;
if($_SESSION['count']>=$downloadHits){//limit reached. Add IP to blacklist
$jsonArray[]=[
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
//save changes
file_put_contents($jsonFile,json_encode($jsonArray));
exit;
}
echo 'good to go!'; //allow the download
Happy coding.
Figured it out after spending some time under the session tag. These two questions were helpful:
How do check if a PHP session is empty?
How can I clear my php session data correctly?
Which led me to code:
session_start();
$jsonFile = 'foobar.json';
$jsonArray = json_decode(file_get_contents($jsonFile), true);
$theIP = $_SERVER['REMOTE_ADDR'];
$addMin = 1; // set value for testing purposes
$addHour = 0; // set value for testing purposes
$targetedHits = 5; // set value for testing purposes
$timeLater = time() + ($addMin*60) + ($addHour*60*60);
if (empty($_SESSION['count'])) {
$_SESSION['expire'] = $timeLater;
}
if (!empty($theIP) && !empty($jsonArray)) {
// look for the $theIP
if (in_array($theIP,array_column($jsonArray,'ip'))) {
$_SESSION['count'] = 0;
session_destroy();
echo 'IP found in json';
exit;
}
if (time() < $_SESSION['expire']) {
echo 'below the time ';
$_SESSION['count'] = isset($_SESSION['count'])? $_SESSION['count'] + 1 : 1;
if ($_SESSION['count'] > $targetedHits) {
echo 'session count reached max ';
$jsonArray[] = [
'ip' => $theIP,
'date' => date("H:i"),
'time' => date("m.d.y")
];
// save changes
file_put_contents($jsonFile,json_encode($jsonArray));
unset($_SESSION['count']);
session_destroy();
exit;
}
} elseif (time() > $_SESSION['expire']) {
echo 'nuking session and counter';
$_SESSION['count'] = 0;
unset($_SESSION['expire']);
}
}
echo '<pre>';
var_dump($_SESSION);
echo '</pre>';
I hope the above helps the next person because I didn't really know anything about sessions and it has been an adventure getting this to work this evening.

Limit array size in cookie

I have the following function to set a cookie on each indiviual product page a user visits on my website.
function setcookie() {
$entry_id = '787';
if (isset($_COOKIE['recently_viewed'])) {
$currentSession = unserialize($_COOKIE['recently_viewed']);
if (!in_array($entry_id, $currentSession)) {
if (count($currentSession) > 5) {
unset($currentSession[0]);
}
$currentSession[] = $entry_id;
} else {}
$currentSession = serialize($currentSession);
setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');
} else {
$recently_viewed[] = $entry_id;
$currentSession = serialize($recently_viewed);
setcookie('recently_viewed', $currentSession, pow(2,31)-1, '/', '');
}
}
In this function I am trying to limit the number of items stored in the cookies array.
When the cookies array has 6 items in it, I want to remove the first (oldest) item in that array and then add the new item (so there is never more than 6 items, but always adds the new one).
I have used the following, but it doesn't always seem to work. Sometimes it removes the first item when there are more than 5, but other times it just keeps adding them so there are more than 6.
if (count($currentSession) > 5) {
unset($currentSession[0]);
}
Can anyone tell me if there is a better way to achieve this?
You definitely should use session.
session_start();
$entry_id = '788';
if (!is_array($_SESSION['recently_viewed'])) {
$_SESSION['recently_viewed'] = array();
}
// add the item to the begining
array_unshift($_SESSION['recently_viewed'], $entry_id);
// ensure unique entries
$_SESSION['recently_viewed'] = array_unique($_SESSION['recently_viewed']);
// keep first 5 entries
$_SESSION['recently_viewed'] = array_slice($_SESSION['recently_viewed'], 0, 5);
echo 'recent: ' . print_r($_SESSION['recently_viewed'], true);
if (count($currentSession) > 5) {
$arr = array_shift($currentSession);
}

Baffled as to why PHP is giving simple logic error on if statement

Like the title says, PHP is really confusing me on a simple if comparison statement that's returning the opposite of what it should be returning. I'm trying to compare 2 datetime's that are first converted to strings:
//Fetched db query, this returns 2012-06-23 16:00:00
$databaseDateTime = strtotime($row['time']);
//This now returns 1340481600
//today's date and time I'm comparing to, this returns 2012-06-22 17:14:46
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
//this now returns 1340399686
Great, everything works perfect so far. Now here's where things get hairy:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
And this returns 'past', which of course it shouldn't. Please tell me I'm missing something. My project kind of depends on this functionality being airtight.
**EDIT***
Thanks guys for taking the time to help me out. Let me post the entire code because a few of you need more context. The request is coming from an IOS5 to my backend code and json is being sent back to the phone.
<?php
//all included files including $link to mysqli_db and function sendResponse()
function getEvents($eventType, $eventArray) {
global $link;
global $result;
global $i;
global $todaysDateTime;
foreach ($eventArray as $key => $value) {
$sqlGetDeal = mysqli_query($link, "SELECT time FROM deals WHERE id='$value' AND active='y' LIMIT 1") or die ("Sorry there has been an error!");
while ($row = mysqli_fetch_array($sqlGetDeal)) {
//compare times to check if event already happened
$databaseDateTime = strtotime($row['time']);
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
$result[$i] = array(
'whenDeal' => $eventType,
'time' => $databaseDateTime,
);
$i++;
}//end while
}//end foreach
}
if (isset($_GET['my'])) {
//$_GET['my'] comes in as a string of numbers separated by commas e.g. 3,2,6,3
$myDeals = preg_replace('#[^0-9,]#', '', $_GET['my']);
$todaysDateTime = strtotime(date("Y-m-d H:i:s"));
$result = array();
$kaboomMy = explode(",", $myDeals);
$i = 1;
if ($myEvents != "") {
getEvents('future', $kaboomMy);
}//end if
sendResponse(200, json_encode($result));
} else {
sendResponse(400, 'Invalid request');
} //end $_POST isset
?>
Found a quick hack around the issue. I just added a local variable to my function and rearranged my compare statement
//added local variable $eventTyppe to function
$eventTyppe;
changed compare from:
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
to:
if ($todaysDateTime < $databaseDateTime ) {
$eventTyppe = $eventType;
} else {
$eventTyppe = 'past';
}
Notice if I rearrange compare:
if ($databaseDateTime < $todaysDateTime ) {
$eventTyppe = 'past';
} else {
$eventTyppe = $eventType;
}
I still get the same error. This is the weirdest thing I've ever seen and the first PHP bug I've run into (I'm assuming it's a PHP bug).
Could you print the values of the times right before this line?
if ($databaseDateTime < $todaysDateTime) { $eventType = 'past'; }
Since that one is declared as global I'm wondering if is it coming back incorrectly.

How do I block a user temporarily

I want to block visitor between 2 to 5 minutes every 100 view.. if user view 100 page between 2 to 5 minutes then block user, if user view 100 view in 6 minutes then don't block and reset the counter.
I already create the counter script but i have issue with creating the function which can block visitor between 2-5 mint.
I need help to fix this problem... I try to create a if condition but no luck.. help me please...
$sb_current_time = date("Y-m-d H:i:s", Time());
/////////////////// Cookies Encryption //////////////
function encrypt($text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$text_num = str_split($text, $bit_check);
$text_num = $bit_check - strlen($text_num[count($text_num) - 1]);
for ($i = 0; $i < $text_num; $i++) {
$text = $text . chr($text_num);
}
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
$decrypted = mcrypt_generic($cipher, $text);
mcrypt_generic_deinit($cipher);
return base64_encode($decrypted);
}
//////////////// Encription end /////////
////// Cookies decription /////
function decrypt($encrypted_text)
{
$key = "E4HD9h4DhS23DYfhHemkS3Nf"; // 24 bit Key
$iv = "fYfhHeDm"; // 8 bit IV
$bit_check = 8;
$cipher = mcrypt_module_open(MCRYPT_TRIPLEDES, '', 'cbc', '');
mcrypt_generic_init($cipher, $key, $iv);
if ($encrypted_text != "") {
$decrypted = mdecrypt_generic($cipher, base64_decode($encrypted_text));
mcrypt_generic_deinit($cipher);
$last_char = substr($decrypted, -1);
for ($i = 0; $i < $bit_check - 1; $i++) {
if (chr($i) == $last_char) {
$decrypted = substr($decrypted, 0, strlen($decrypted) - $i);
break;
}
}
}
return $decrypted;
}
///////// Coookies decription end /////////////////
//$sb_check_ban_time = date($sb_current_time, strtotime("+20 minute"));
if ($_COOKIE['spamer_check_time'] == "") {
setcookie('spamer_check_time', encrypt(time()));
}
function time_deff($date2)
{
$date1 = time();
//sleep(2000);
// $date2 = decrypt($_COOKIE['spamer_check_time']);
//echo $date2;
$mins = ($date1 - $date2) / 60;
//echo $mins;
return $mins;
}
//$sb_cookie_expiration = time() + 1200;
//echo $sb_cookie_expiration;
if ($_COOKIE['view2'] != "") {
$explod = explode("-", decrypt($_COOKIE["view2"]));
}
$i_print = $explod[0];
// $i2=$explod[1];
//echo $i2;
$i = 1 + $i_print;
setcookie("view2", encrypt($i . "-123456789")); //// Need to add extra bit to block unwanted text and secure the cookes more..
//
$i = $i++;
// echo $i_print;
//echo "empty".decrypt($_COOKIE["spamer_check_time"]);
$spammer_blocker = decrypt($_COOKIE["spammer_blocker"]);
// or $spammer_blocker==""
$mins = time_deff(decrypt($_COOKIE['spamer_check_time']));
$diff_time = .1; /// User BLock Time
if ($mins >=1 or $mins <=2) {
$block_user=1;
} elseif ($mins >= 2.1) {
$block_user=2;
} else {
}
/* if (.2>$mint) {
// echo "not done";
$block_user=0;
} elseif (.2 <= $mint) {
echo "block User";
$block_user=1;
} elseif ($mins>=1) {
echo "reset cookies";
$block_user=2;
}*/
if ($block_user==1 and $i_print >= 15) {
if ($spammer_blocker == "") {
setcookie("spammer_blocker", encrypt(time()));
header('HTTP/1.1 403 Forbidden');
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
} else {
//$sb_check_ban_time = $spammer_blocker;
$diff_block_time = time_deff($spammer_blocker);
//echo $diff_block_time;
//$sb_check_ban_time = date($spammer_blocker, strtotime("+1 minute"));
if ($diff_time <= $diff_block_time) {
/// echo "Delete the IP and cookies";
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
} else {
//echo "Still Block"; /// echo "Still Block";
header('HTTP/1.1 403 Forbidden');
// echo "IP Block for Spaming wait few mint";
$time_rev = $diff_block_time - $diff_time;
$round_time = round($time_rev, 2);
$time_reverse = str_replace('-', '', $round_time);
echo "Wait " . $time_reverse . " Minuts before using this site..";
exit(0);
}
}
} elseif ($block_user==2) {
setcookie("spammer_blocker", "");
setcookie("view2", "");
setcookie("spamer_check_time", "");
echo "cookies reset";
} else {
}
First, you need to know who they are...
For casual users, you can rely on cookies. But if you are having problem with an abuser, then they will simply ignore your attempt to stop them and not send a cookie.
There are various levels of knowing "who" someone is.
ID in URL
Cookies
IP Address
And they can ALL be overcome with different levels of diffulculty...
Way too easy (just spoof a different ID, etc...)
Cookies are the same as #1
IP addresses are harder to overcome unless you have a botnet or similar
For your case, you should likely block the IP address as it's the only reasonable way for you to get done what you are looking for.
--
Next, you need to be able to keep track of their connections. iptables in Linux has a way to track the number of connections and block for a specific number of minutes after a certian threshold is reached.
Using only PHP, you need to record each hit, and the IP address of that hit. An SQL database would be one of the more efficient ways of doing this.
If you don't care about history, then simply (mysql):
INSERT INTO HitTable SET IP=..., Visits=1
ON DUPLICATE KEY UPDATE Visits=Visits+1
A background crontab could run a query like this every minute?
UPDATE HitTable SET Visits = Visits - 10
DELETE FROM HitTable WHERE Visits < 1
Finally, when a visitor visits, you would check the database table for
SELECT Visits<100 WHERE IP=...
AND if that returns True, let them in, else block them.
Hope this helps a bit.
Storing the timeout value in a cookie will be absolutely trivial for a user to change/delete the cookie
Storing it in a session variable is a bit more reliable, but again - the user could just delete the session cookie, get a new session going, and start reading again.
That being said, you'd do something like this:
<?php
session_start();
if (user_should_be_blocked()) {
$_SESSION['blocked_start_time'] = time();
header("Location: timeout.html");
}
if ($_SESSION['blocked_start_time'] > (time() - 300)) {
header("Location: timeout.html");
}
// got here, must not be blocked and/or timeout has expired
$_SESSION['blocked'] = false;
$_SESSION['block_start_time'] = null;
.... continue on
I would use the header funciton to redirect them to another page, either empty or just less bankwidth intensive (assuming that's why you're making this anyway). Soemthing like...
if ($block_user == 1)
header("Location: blockPage.php");
At the top of all pages you need to block.
Edit: actually, come to think of it, (2) is of course not necessary, if 2 people or 2 computers are logged in they'll only consume their alloted amount of views faster..
You can do this provided:
A user needs to be logged in to see the pages.
You don't allow the same user(name) to be logged in twice with different sessions.
You store the count per-user, not per-session or per-ip/whatever.
(2) is not possible with default file based sessions. A custom database or other persistent storage solution is needed in which you can scan for other session-id's of a current user-id. In a database you would just store a user-id field, a custom memcached solution could also be built, etc. To prevent users being locked out of a session they no longer have my solution was always to destroy any old session a user had the moment they log in. Effectively, if it's tried with multiple sessions/ips, they'll have to log in again and again invalidating the previous session.
(3) again some persistent storage with a timestamp+userid+count (in MySQL's case an INSERT INTO tablename (user_id,time,count) VALUES (<id>,NOW(),1) ON DUPLICATE KEY UPDATE count=count+1 comes to mind to easily increment view counts.
And on every view query the database again and again about how many views the visitor had the last X minutes.

Categories