How do I block a user temporarily - php

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.

Related

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.

I need help fixing this code

So, I made a PHP page/link checker, which should not allow an user to visit/redirect to a page if isn't passed certain minutes from last visit/redirect.
The problem is, the user is being redirected to the page ALWAYS even if he already did it 1 min ago and the timer is 7 min (example). The timer is setted into MySQL as minutes.
can't figure out what is wrong in the code
this is the first page:
<?php
session_start();
$sql = "SELECT * FROM table_records";
$result = mysql_query($sql);
$records = array();
while ($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
foreach ($records as $record) {
$now = new DateTime();
if (!array_key_exists($record, $_SESSION['records']) || ($now->getTimestamp()-$_SESSION['records'][$record]) <= 600) {
echo "<td><center>".$record['id']."</center></td>";
echo "<td><center>".$record['name']."</center></td>";
echo "<td><center>".$record['link']."</center></td>";
echo "<td><center>".$record['delay']."</center></td>";`
} else {
// link disabled
}
}
?>
and this is the page the users are redirected to, to check the timer, and in case redirect them to the link.
$waiting_time = $delay * 60; //calculate delay time in seconds
if (!array_key_exists($id, $_SESSION['records'])) {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
} elseif (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) >= $waiting_time) {
echo "Looks like you already visited this page";
} elseif (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) < $waiting_time) {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
}
The problem is, the user is being redirected to the $link ALWAYS, even if he already visited, and the time of delay isn't passed.
What is wrong with the code?
DRY, you can write your if/elseif statements much easier:
if (array_key_exists($id, $_SESSION['records']) && ($now->getTimestamp()-$_SESSION['records'][$id]) < $waiting_time) {
echo "Looks like you already visited this page";
} else {
$_SESSION['records'][$id] = $now->getTimestamp();
header("Location: $link");
exit();
}
Now, if you look at it you'll see there are two things to check at first:
Is $_SESSION['records'] not empty (maybe session wasn't intialized on second page?) - var_dump ($_SESSION['records']) - what's in there?
what's the result of ($now->getTimestamp()-$_SESSION['records'][$id]) and what's in $waiting_time variable - var_dump it
Don't forget to call exit() after dumping the code and before redirection or simply comment location () lines, otherwise you'll see nothing
Third possibility (you'll know this is the case if you don't see var_dump printout) is that your browser remembers 301 redirection and when you go second time to same address it redirects automatically without calling your script - restart your browser or try different one.

PHP Session custom class sessions not being set?

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
(
)

php/ajax random characters and countdown

I'm trying to simulate The words game in as3.
The same random characters or all users and 2 minutes countdown is needed
I've a code That generate 25 random characters. How Can I Show The Random Characters For all Users ?
<?PHP
function randStr($rts=20) {
$act_chars = "ABCÇADAEFGĞHEIİJKELMNOAÖPRKSŞTUÜVYZ";
$act_val = "";
for($act=0; $act <$rts ; $act++) {
mt_srand((double)microtime()*1000000);
$act_val .= mb_substr($act_chars, mt_rand(0, mb_strlen($act_chars)-1), 1);
}
return $act_val;
}
$dene = randStr(25);
print "izinliharfler=$dene";
?>
maybe I need to use cron job, I do not know
You Can Store The Generated string (Characters String) In A Table,
Then Create An ajax call To Pull It For All Users.
You can use ip address of the user and then change seed accordingly.
<?PHP
function randStr($rts=20,$ip) {
$act_chars = "ABCÇADAEFGĞHEIİJKELMNOAÖPRKSŞTUÜVYZ";
$act_val = "";
for($act=0; $act <$rts ; $act++) {
mt_srand((double)microtime()*1000000+$ip);
$act_val .= mb_substr($act_chars, mt_rand(0, mb_strlen($act_chars)-1), 1);
}
return $act_val;
}
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$dene = randStr(25,$ip);
print "izinliharfler=$dene";
?>

Advanced PHP: Allow a unique URL to be clicked by the first three IPs only

I am selling a subscription viewing service. Once people have paid they get a unique URL e-mailed to them. The link is set to expire after a certain time but I'd like to only allow the first three IP addresses to use the link before it expires to stop piracy. I'm doing it like this to avoid having yet another database running holding thousands of logins. I assume I can write to a directory and have a filename as the suffix of the link (zFZpj4b2AkEFz%2B3O in this case) with up to three IPs listed in the file.
It all works well so far barring the IP address counting and the unique link the e-mail looks like this:
http://www.blah.com/download.php?file=zFZpj4b2AkEFz%2B3O
The file download.php looks like this:
<?
$time = time();
include('settings.php');
class RC4Crypt {
/**
* Encrypt the data.
* #param string private key.
* #param string data to be encrypted.
* #return string encrypted string.
*/
function encrypt ($pwd, $data)
{
$key[] = '';
$box[] = '';
$pwd_length = strlen($pwd);
$data_length = strlen($data);
for ($i = 0; $i < 256; $i++)
{
$key[$i] = ord($pwd[$i % $pwd_length]);
$box[$i] = $i;
}
for ($j = $i = 0; $i < 256; $i++)
{
$j = ($j + $box[$i] + $key[$i]) % 256;
$tmp = $box[$i];
$box[$i] = $box[$j];
$box[$j] = $tmp;
}
$cipher = '';
for ($a = $j = $i = 0; $i < $data_length; $i++)
{
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a];
$box[$a] = $box[$j];
$box[$j] = $tmp;
$k = $box[(($box[$a] + $box[$j]) % 256)];
$cipher .= chr(ord($data[$i]) ^ $k);
}
return ($cipher);
}
/**
* Decrypt the data.
* #param string private key.
* #param string cipher text (encrypted text).
* #return string plain text.
*/
function decrypt ($pwd, $data)
{
return RC4Crypt::encrypt($pwd, ($data));
}
}
if(!isset($_GET['file']) || empty($_GET['file'])) {
echo 'Invalid Request';
return;
}
$data = $_GET['file'];
$id_time = RC4Crypt::decrypt($secret,base64_decode(rawurldecode($data)));
list($product_id,$timestamp) = explode('|',$id_time);
if(!isset($products[$product_id])) {
echo 'Invalid Request';
return;
}
if ($timestamp < $time - ($download_life * 60 )) {
echo 'Link Expired';
return;
}
if(isset($products[$product_id])) {
print ("<html><head><meta http-equiv=Refresh content=\"0;URL=http://www.blah.com/view/\"></head><body></html>");
return;
}
?>
Can any kind soul take pity on someone who has spent far too long looking at this already please ? :) Thanks very much.
--EDIT --
A thought: Forgetting the 3 IPs what about storing a Server-side cookie when the link is pressed the first time and denying access if it exists ?
To do this, you have to create a table for each subscription.
table subscription: subId, subCode, subVisitTimes, subVisitedIP
subCode will be something like zFZpj4b2AkEFz%2B3O
for each visit, you get client's IP using $_SERVER['REMOTE_ADDR'].
If it does exist in subVisitedIP then allow access.
If it does not exist then check subVisitTimes value:
if subVisitTimes = 3 then deny access
If subVisitTimes < 3 then allow access and increase its value by one also add client's IP to subVisitedIP (you should use serialize function to store array of three IPs).
You're going to want to set up a simple database for this. You only need one row - the hash/id, the original IP, expired, etc and can simply set expired to 1 when access runs out. This way you're not running costly DELETE queries, and if need be you can simply delete those rows all at once a couple times a month to save space.
Otherwise it's going to get too complex and more error-prone using flatfiles.

Categories