HTTP Referrer through Age Gate - php

I have an age gate set up on my site, so that users under 17 can't enter the site, but I want people, who have bookmarked a specific link to be able to go to that link after passing through the age gate:
Here is my age gate code:
<?php
session_start();
if(isset($_SESSION['legal'])) { # Check to see if session has already been set
$url = ($_SESSION['legal'] == 'yes') ? 'index.php' : 'message.php';
header ('Location: ' .$url);
}
// If visitor hasn't gone through the age gate - Age Gate function and Set Session//
if(isset($_POST['checkage'])) {
$day = ctype_digit($_POST['day']) ? $_POST['day'] : '';
$month = ctype_digit($_POST['month']) ? $_POST['month'] : '';
$year = ctype_digit($_POST['year']) ? $_POST['year'] : '';
$birthstamp = mktime(0, 0, 0, $month, $day, $year);
$diff = time() - $birthstamp;
$age_years = floor($diff / 31556926);
if($age_years >= 18) {
$_SESSION['legal'] = 'yes';
$url = 'index.php';
} else {
$_SESSION['legal'] = 'no';
// If failed the Age Gate go to specific page
$url = 'message.php';
}
header ('Location: ' .$url);
}
?>
What can I add to this code so that if I wanted to go to domain/page.php or domain/subdirectory/ -- the Age Gate will take me there after I pass it? (I know I have to use HTTP Referrer, but I can't figure out how to include it).
Edit to Add : I know that sometimes Browsers will not keep/send the HTTP Referrer, so I will need a solution for those who don't pass that value.
EDIT : AGE Calculation based on the form submission -
$day = ctype_digit($_POST['day']) ? $_POST['day'] : '';
$month = ctype_digit($_POST['month']) ? $_POST['month'] : '';
$year = ctype_digit($_POST['year']) ? $_POST['year'] : '';
$birthstamp = mktime(0, 0, 0, $month, $day, $year);
$diff = time() - $birthstamp;
$age_years = floor($diff / 31556926);

I'd setup this the other way around: have each page set a $_SESSION variable to indicate where to go:
if (!isset($_SESSION['legal']) || $_SESSION['legal'] == 'no') {
$_SESSION['target'] = $_SERVER['PHP_SELF'];
header('Location: message.php');
return;
}
// continue script execution...
And in your message.php:
$isLegal = check_age(); // your age checking logic
if ($isLegal && isset($_SESSION['target'])) {
header('Location: ' . $_SESSION['target']);
} else if ($isLegal) {
header('Location: index.php');
} else {
// setup message.php with a validation failed message
}
Mind, this is just one of the possible variations, but I'd suggest not relying on user data such as the referrer (some browser extensions even explicitly unset/modify that).

Related

Show different time when at different country

Want to ask.
How do I create a website that is able to show different time when at different country.
Example:
If user is using the website at Japan, it will show Japan's time.
While If user is using the website at Britain, it will show Britain's time.
Right now I am using this code:
<?php
date_default_timezone_set("Asia/Tokyo");
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
?>
You should do it on the client-side. I have read a forum once and they recommended it to be done in the client per se. Take what you think might help you from this javascript code example:
var now = new Date();
var utcString = now.toISOString().substring(0, 19);
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var localDatetime = year + "-" +
(month < 10 ? "0" + month.toString() : month) + "-" +
(day < 10 ? "0" + day.toString() : day) + "T" +
(hour < 10 ? "0" + hour.toString() : hour) + ":" +
(minute < 10 ? "0" + minute.toString() : minute) +
utcString.substring(16, 19);
//var datetimeField = document.getElementById("myDatetimeField");
//datetimeField.value = localDatetime;
alert(localDatetime);
There is no function in php that can get user based timezone. But there is way around. First you have to grab user IP address, then you have make a call to a third party service to get geo information. Thus you can get user timezone.
The following function is fool-proof solution to get user IP using php so far. And credits goes to https://stackoverflow.com/a/38852532/7935051
<?php
function getClientIp() {
$ipAddress = '';
if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ipAddress = $_SERVER['HTTP_CLIENT_IP'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_X_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_X_FORWARDED'];
} elseif (isset($_SERVER['HTTP_FORWARDED_FOR'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED_FOR'];
} elseif (isset($_SERVER['HTTP_FORWARDED'])) {
$ipAddress = $_SERVER['HTTP_FORWARDED'];
} elseif (isset($_SERVER['REMOTE_ADDR'])) {
$ipAddress = $_SERVER['REMOTE_ADDR'];
} elseif (getenv('REMOTE_ADDR')) {
$ipAddress = getenv('REMOTE_ADDR');
} else {
$ipAddress = 'Unknown';
}
return $ipAddress;
}
Now you have to depend on the third party services to get geo information. This is very true for this type of jobs. There are several free services on internet, for example, geoPlugin. You may use it. See more details.
// Gets the client IP
$userIp = getClientIp();
$geoInfo = unserialize(file_get_contents("http://www.geoplugin.net/php.gp?ip={$userIp}"));
// Gets the timezone
$timezone = $geoInfo['geoplugin_timezone'];
// Sets user timezone, otherwise uses default
if ($timezone) {
date_default_timezone_set($timezone);
} else {
date_default_timezone_set('Asia/Tokyo');
}
echo "Today's date is :";
$today = date("d/m/Y");
echo $today;
BTW you may debug $geoInfo variables to get more information

PHP, Fire cookies on condition of pages

I'm having some trouble firing cookies on the condition of what page the user visits first.
Code below fires a cookie if on pages 2641, 2998, 2949 and no cookie exists. However, how do I do it to fire a different cookie if user is on any other page on the website if no cokkies exist?
Rule: Two cookies cannot exist. Just one or the other.
Any help much appreciated :)
if (is_page([2641,2998,2949]) && !isset($_COOKIE['ppc_campaign']) && !isset($_COOKIE['organic'])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
}
Sounds like this is what you want. Check for cookie existence. If neither exists, check the specific page, otherwise do something else.
if (!(isset($_COOKIE['ppc_campaign']) || isset($_COOKIE['organic']))) {
if (is_page([2641,2998,2949])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
$organic_cookie = "organic";
$organic_value = "?campaign=_ORGANIC_";
$path = "/";
setcookie($organic_cookie, $organic_value, time() + (86400 * 28), $path);
$acf_applicationLink = $organic_value;
}
}

PHPbb redirect to certain page if its first of the month

All,
I have been trying to get my instance of PHPBB to redirect to a certain page if it is the first of the month. All other days of the month I want the redirect to the index page.
I have tried modifying the includes/functions.php to include the redirect and the ucp.php page to include the new redirect.
includes/functions.php:
// The result parameter is always an array, holding the relevant information...
if ($result['status'] == LOGIN_SUCCESS)
{
date_default_timezone_set('EST');
$firstday = date('Y-m-01');
$today = date('Y-m-d');
if ($firstday == $today){
$redirect = request_var('redirect', "{$phpbb_root_path}projects/index.$phpEx");
$message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
$l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}projects/index.$phpEx" || $redirect === "projects/index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
}
else{
$redirect = request_var('redirect', "{$phpbb_root_path}index.$phpEx");
$message = ($l_success) ? $l_success : $user->lang['LOGIN_REDIRECT'];
$l_redirect = ($admin) ? $user->lang['PROCEED_TO_ACP'] : (($redirect === "{$phpbb_root_path}index.$phpEx" || $redirect === "index.$phpEx") ? $user->lang['RETURN_INDEX'] : $user->lang['RETURN_PAGE']);
}
// append/replace SID (may change during the session for AOL users)
$redirect = reapply_sid($redirect);
and the ucp.php:
case 'login':
date_default_timezone_set('EST');
$firstday = date('Y-m-30');
$today = date('Y-m-d');
if (($user->data['is_registered']) && ($today == $firstdate))
{
redirect(append_sid("{$phpbb_root_path}projects/index.$phpEx"));
}
else{
redirect(append_sid("{$phpbb_root_path}index.$phpEx"));
}
login_box(request_var('redirect', "index.$phpEx"));
break;
However using one or both of these does not return a successful redirect. The user is logged in and a
This page cannot be displayed.
message shows up.
Is there a better way of doing this?
It would be nice to get this redirect to work.

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.

php $_GET['page'] several pages

if (!$_GET['page'] || preg_match('/\W/', $_GET['page']) || !file_exists('./intl/tpl/tpl_source/' . $_GET['page'] . '.tpl'))
$_GET['page'] = 'index';
if ($_GET['page'] && $_GET['page'] != 'index') {
$smarty->assign("pg_" . $_GET['page'], true);
$smarty->display($_GET['page'] . ".tpl");
die();
}
This code let me open any page (?page=1, ?page=2 and so on, also it's mean if no page give, open index)
but i need specify which one user can open, so, code should look like:
if ($_GET['page'] = '21' || preg_match('/\W/', $_GET['page']) || file_exists('./intl/tpl/tpl_source/' . $_GET['page'] . '.tpl')) {
//my stuff
}
In short, i need specify which addresses user can open with $_GET['page'] (?page=21 ?page=22 and so on).
Sorry if question not clear.
You can simplify your code by using a typecast (for filtering!) and a simpler list of allowed pages:
$allowed_pages = array(1, 12, 21, 25, 32);
$page = (int)$_GET["page"]
and in_array($page, $allowed_pages)
and file_exists("./intl/tpl/tpl_source/$page.tpl")
or $page = "index";
$smarty->assign("pg_$page", true);
$smarty->display("$page.tpl");
die();
You can create a white list:
var $pages = array(
21 => true,
22 => true
);
// or
var $pages = array_flip(array(21, 22));
and test whether the page is in there:
if(isset($pages[$_GET['page']])) {
}

Categories