expiring php redirect on set date - php

I.m looking for a way in Php to have a Redirect expire on a said day.
The use for this is that I'm sharing file on a sever using the code below.
What I like is to have that redirect take them to a page that lets them know there time is up and they can see the Redirect anymore or tell I update the date of expire.
if (test){
---do something---
die("<script>location.href = 'http://file.here.com'</script>");
} else {
return false;
}
I have also try
function BeforeProcessList(&$conn, &$pageObject)
{
$target_date = new DateTime("05-01-2014");
$today = new DateTime();
if((int)$target_date->diff($today)->format('%r%a') >= 0)
{
header("Location: testview_list.php");
exit();
}
}

There are several scenarios for this case but i suggest to use session.
Use additional session to be taken once your privilege period is valid and make sure that you've already insert a date when a user get into that file along with value that indicate this user is allowed , for example,1 so you can change a value to ,for example,0 after specific period and that user will be denied automatically or redirected to another page

I got it to work.
<?php
// has this expired?
$expire_date = "2015-08-25"; // good until Aug 8/15
$now = date("Y-m-d");
if ($now>$expire_date) {
header("Location: http://yoursite.com/outoftime.html");
die();
}
// and now the unexpired part of the page ...
header("Location: http://yoursite.com/fileshare/");
die();
Thanks for the help guys

Related

Making the variable unset after two minutes

Hey guys am writing a small validation script which uses a simple token to login from the input..When the token is right the user must succesfully login and after two minutes the token must expire and give user a message token expired..But here when i use the token it also came with the message token destroyed ..i want to use the token for 2 minutes and i want the token to be expired in 2 minutes.
I have the html file
<form action="gethints.php" method="post">
First name: <input type="text" name="fname"><br>
<input type="submit" value="Submit">
</form>
Php file
<?php
$name = $_POST['fname'];
$currenttime = time();
$token = 'sample';
$timetounset = strtotime("2 minutes");
if($name != $token) {
echo 'you cant login';
} else {
echo 'you have succesfully logged in <br>';
}
if($currenttime > time() - $timetounset) {
unset($token);
echo "you cant use this token anymore";
} else {
echo 'token is not destroyed';
}
When i run this code and type sample in the input box i get the message like
you have succesfully logged in
you cant use this token anymore
What i need is when i type the id as sample i want to get the message you have succesfully logged in and after two minute when i use the same id i need to get the message like you cant use this token anymore
Thanks for your help..
Could use a session here:
first, store the last time the user made a request
<?php
$_SESSION['timeout'] = time();
?>
in subsequent request, check how long ago they made their previous request
<?php
if ($_SESSION['timeout'] + 2 * 60 < time()) {
// session timed out
} else {
// session ok
}
?>
EDIT:
Don't forget to have session_start(); on top of your code && check if $_SESSION['timeout'] exists, above code is just an example.
The most simple way to approach this imo is to set a cookie with an expiration of 2 minutes.
Store a variable or flag in the cookie and check the contents each time you want to do a validation.
setcookie("TestCookie", $value, time()+120);
Read out the value:
if (isset($_COOKIE['TestCookie'])) {
// Good cookie
} else {
// expired or invalid
}
For information on how to set a cookie and expiration:
http://php.net/manual/en/function.setcookie.php
People can play around with cookies. I suggest you create a database table tokens with token and expires columns. When you insert the token add this to your sql. ...... Insert ....... Timestampadd(now(), interval minute 2); To validate just check if now() is less than expires.

need to refresh page to remove sessions

In this code I'm trying to ban client if he/she/it doing to much(10) login request for 3 minutes. The problem is after 3 minutes user must refresh the page 2 times. I can see the reason why it's enter into if statement but I can't find the solution. I feel like I've overcoded.
if($this->sessions->get_data("wrong_login")>10){
if(!isset($_SESSION["ban_time"])){
$this->sessions->set_data("ban_time", time());
}else
{
if(time() - $this->sessions->get_data("ban_time") > 180){ // 180 seconds
$this->sessions->remove("ban_time");
$this->sessions->remove("wrong_login");
}
}
// The message if user still banned
die("Banned for 3 minutes!");
}
I hope I can tell the problem..
EDIT: This code is the inside of the construct of register controller.
Before your IF statement, add another if statement that checks for ban_time session if the time is up, then set the wrong_login session to 0 if it is.
if($this->sessions->get_data("ban_time") < time())
{
$this->sessions->remove("ban_time");
$this->sessions->set_data("wrong_login", 0);
}
remove your else statement there.
also forgot to mention! when you set the ban time, it should be time() + 180.
if(!isset($_SESSION["ban_time"])){
$this->sessions->set_data("ban_time", time()+180);
}
use header function.
e.g.
header("Location: /path/to/some/file.php?error=Banned for 3 minutes.");
Then on the file.php you can do this:
<?php
// Parse error
$error = isset($_GET['error']) ? $_GET['error'] : '';
// Display error (if any) and stop executing the rest of the code.
if (!empty($error)) {
exit($error);
}
?>
This will not work if you already started to output...

How to build codeigniter login page and session with one controller

Hi. I am having a problem with my sessions, I am new to CodeIgniter, so please be patient with me. Here's my index function:
function index()
{
$username;
$pWord; //assume these two variables has valid and correct value
if($this->coreModel->authenticate($username, $pWord)){
$user = $this->coreModel->authenticate($username, $pWord);
foreach($user->result() as $key) {
$this->session->set_userdata(array(
'logged_in' => TRUE,
'cl_UserId' => $key->cl_UserId,
'cl_username' => $key->cl_username,
'cl_roles' => $key->cl_roles));
if($this->session->userdata('cl_roles') == 1){
header("Location: ".base_url()."controller/homepage");
} else {
$this->load->view('loginPage',$this->data);
}
}
} else {
//$this->data['msg'] = "Wrong Username/Password";
$this->load->view('loginPage',$this->data);
}
}
function kickIfNotInSession(){
if ($this->session->userdata('logged_in') == FALSE)
{
redirect('controller');
}
}
If I enter a valid username and password, it works fine, and the page goes to the homepage. In my homepage, I echo the id and username. Also in my homepage, I have a tabs menu. In all of the pages, I echo the id and username. I have also added a kickIfNotInSession() function in all of the functions, for example:
function test() {
$userid = $this->session->userdata("logged_in");
$this->kickIfNotInSession();
$this->load->view("test");
}
Also, I have autoload.php:
$autoload['helper'] = array('url');
$autoload['libraries'] = array('database','session');
After logging in, I clicked all the tabs and for some reason it works fine. It echoes the id and username, but after a minute or two when I click my tab, it kicks me out of sessions and directs me to the login page. I wonder how that happened. Am I missing something?
Check sess_expiration parameter in application/config/config.php file. May be it set incorrect.
'sess_expiration' = the number of SECONDS you want the session to last. by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
It sounds like your session expriation set to a very low value that throwing you out after few minutes.
Goto application/config/config.php, scroll down and look for $config['sees_expiration'].
That's what sets the expiration time (in seconds). Change it to whatever works for you and try again.
You can also take a look at CodeIgniter manual here (at the bottom of the page).
sess_expiration - The number of seconds you would like the
session to last. The default value is 2 hours (7200 seconds). If you
would like a non-expiring session set the value to zero: 0
You should increase session expiration time. To change expirationtime
Open CI config file located path_to_project/application/config/config.php
Find $config['sees_expiration']
Now incrase expiration like $config['sess_expiration'] = 14400;
Note: Session expiration time will be consider in second.

How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. Every page on my website requires a login, and so users are redirected to a login page on page load. At the top of each page then I have:
<?
require("log.php");
include_once("config.php");
include_once("functions.php");
?>
This redirects the user to log.php (with new code added):
<?
session_name("MyLogin");
session_start();
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");
if (!$q_user) {
die(mysql_error());
}
if(mysql_num_rows($q_user) == 1) {
$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) {
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}
// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}
?>
The login form is contained in login.php. The code for login.pho relevant to the PHP/log.php is:
<?
session_start();
if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>
and
<form name="login_form" id="form" method="post" action="log.php?action=login">
The answer that I came across stated that I should add:
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add:
if(isset($_SESSION['url']))
$url = $_SESSION['url']; // holds url for last page visited.
else
$url = "index.php"; // default page for
to my login page, and use the following URL for redirect on successful login:
header("Location: http://example.com/$url"); // perform correct redirect.
I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php.
I have tried adding it to both, but the login page is just looping once I have entered the username and password.
I wonder if someone could help me get this working?
Thanks,
Nick
It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim.
SCENARIO 1:
If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? Please do note, that the code below, is the code you've posted.
$db = mysql_select_db(""); //put your database name in here
SCENARIO 2:
The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it?
if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement
SCENARIO 3:
If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established
session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];
If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history.
if(!isset($_SESSION['internal_breadcrumbs']))
$_SESSION['internal_breadcrumbs'] = array();
$_SESSION['internal_breadcrumbs'][] = $_SERVER['REQUEST_URI'];
$max_breadcrumbs = 5;
while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
array_shift($_SESSION['internal_breadcrumbs']);
That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following
Array
(
[internal_breadcrumbs] => Array
(
[0] => /other_page.php
[1] => /other_page.php
[2] => /other_page.php
[3] => /user_page.php <-- desired page
[4] => /login.php <-- most recent page
)
)
So now... you can setup your url to be something more like the following...
// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs']))
$url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else
$url = "index.php"; // default page for
All the best, and I certainly hope this has helped in some way.
IN SCENARIO 4
From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure)
If response is right send the login password to your script server.
Stips : Encoding password is better secure !
Using header() function it's a bad idea.
Manual specification say ;
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.
So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes.
Regenerate cookie each time the loging.PHP is called !
Have a nice day

Quick and easy flood protection?

I have a site where a user submits a message using AJAX to a file called like.php. In this file the users message is submitted to a database and it then sends a link back to the user. In my Javascript code I disabled the text box the user types into when they submit the AJAX request.
The only problem is, a malicious user can just constantly send POST requests to like.php and flood my database. So I would like to implement simple flood protection.
I don't really want the hassle of another database table logging users IPs and such... as if they are flooding my site there will be a lot of database read/writes slowing it down. I thought about using sessions, like have a session that contains a timestamp that gets checked every time they send data to like.php, and if the current time is before the timestamp let them add data to the database, otherwise send out an error and block them. If they are allowed to enter something into the database, update their session with a new timestamp.
What do you think? Would this be the best way to go about it or are there easier alternatives?
Thanks for any help. :)
Session is the easiest to do this, and has the least overhead as well. You can store two bits of data in the session, timestamp of last post, and the ip the post is comming from. Here is how you check legitimacy then:
session_start();
if(isset($_SESSION['ip']) && $_SESSION['last_post'] + MININTERVAL < time()) die('too early');
$_SESSION['last_post'] = time();
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
// store the message
Use a token. You generate the token and add it to the page originating the request. In like.php you verify that the request contains a valid token, which means it comes from your page instead of an external one POSTing directly.
You don't need to go through the whole record file. Instead:
<?php
define("FLOODPOOL", ".");
define("FLOODPOOL_LIMIT", 30);
define("FLOODPOOL_DURATION", 60 * 60 * 24);
define("FLOODPOOL_AUTOCLEAN", true);
// Record and check flood.
// Return true for hit.
function floodpool_check($id){
$fp = fopen(FLOODPOOL . DIRECTORY_SEPARATOR . 'fp_' . basename($id), 'a+');
fwrite($fp, pack('L', time()));
if(fseek($fp, -4 * FLOODPOOL_LIMIT, SEEK_END) === -1) {
return false;
}
$time = reset(unpack('L', fread($fp, 4)));
fclose($fp);
if(time() - $time < FLOODPOOL_DURATION) {
if(FLOODPOOL_AUTOCLEAN){
#floodpool_clean();
}
return true;
}
return false;
}
// Clean the pool.
function floodpool_clean(){
$handle = opendir(FLOODPOOL);
while(false!==($entry=readdir($handle))){
$filename = FLOODPOOL . DIRECTORY_SEPARATOR . $entry;
if(time() - filectime($filename) > FLOODPOOL_DURATION && substr($entry, 0, 3) === 'fp_'){
unlink($filename);
}
}
closedir($handle);
}
Usage example:
if(floodpool_check($_SERVER['REMOTE_ADDR'])){
header("HTTP/1.1 429 Too Many Requests");
exit("Hit some *");
}
Another way to do this is to write a hidden form input to the page (that calls like.php) using jQuery. A bot won't be using javascript so your hidden form field won't exist.
Check for the hidden field (assign it a value and a name) and if it exists, then hit the database with the request.
Another way; code a hidden element into the page (<input style='display:none;' name='nospam' value='' />). A bot will auto-fill every field in the form, so you just check if this field is populated - a user can't see it so you know it's a bot if you've got content there.
Set the style (display:none;) using jQuery tho... again, a bot won't see the jQuery, so it will think this is a legit form input.
You may want to specify a 'this page requires javascript to run' notice somewhere for the user. Some alternative suggestions. After all - you said 'simple' ;)
Well I made a script to handle it for core requests only (no session requests or other requests who aren't calling the core). If you have a look to google you'll find scripts/classes which will kill your server because of high loads every time. The fact, that many use SESSIONs and maybe ALSO SQL/Database will let you get a flooding protection as a server-killer. Also the fact that SESSIONs need a Cookie (or a GET SID) so you can manipulate SESSIONs easy to get a new SESSION ID.
My function is text-based and do a simple handling. The bad thing is that you maybe have to use a CronJob to delete ips from time to time. Comparing to other scripts its about 10* faster (and more save than sessions).
I don't know if its really useful at all. ;)
You maybe like to change the rpm value to less or/and also the 200 req. My setting is a ban for a bot doing interval requests in <=6 seconds.
<?php
function ht_request_limiter() {
if (!isset($_SERVER['REMOTE_ADDR'])) { return; } // Maybe its impossible, however we check it first
if (empty($_SERVER['REMOTE_ADDR'])) { return; } // Maybe its impossible, however we check it first
$path = '/your/path/ipsec/'; // I use a function to validate a path first and return if false...
$path = $path.$_SERVER['REMOTE_ADDR'].'.txt'; // Real file path (filename = <ip>.txt)
$now = time(); // Current timestamp
if (!file_exists($path)) { // If first request or new request after 1 hour / 24 hour ban, new file with <timestamp>|<counter>
if ($handle = fopen($path, 'w+')) {
if (fwrite($handle, $now.'|0')) { chmod($path, 0700); } // Chmod to prevent access via web
fclose($handle);
}
}
else if (($content = file_get_contents($path)) !== false) { // Load existing file
$content = explode('|',$content); // Create paraset [0] -> timestamp [1] -> counter
$diff = (int)$now-(int)$content[0]; // Time difference in seconds from first request to now
if ($content[1] == 'ban') { // If [1] = ban we check if it was less than 24 hours and die if so
if ($diff>86400) { unlink($path); } // 24 hours in seconds.. if more delete ip file
else {
header("HTTP/1.1 503 Service Unavailable");
exit("Your IP is banned for 24 hours, because of too many requests.");
}
}
else if ($diff>3600) { unlink($path); } // If first request was more than 1 hour, new ip file
else {
$current = ((int)$content[1])+1; // Counter + 1
if ($current>200) { // We check rpm (request per minute) after 200 request to get a good ~value
$rpm = ($current/($diff/60));
if ($rpm>10) { // If there was more than 10 rpm -> ban (if you have a request all 5 secs. you will be banned after ~17 minutes)
if ($handle = fopen($path, 'w+')) {
fwrite($handle, $content[0].'|ban');
fclose($handle);
// Maybe you like to log the ip once -> die after next request
}
return;
}
}
if ($handle = fopen($path, 'w+')) { // else write counter
fwrite($handle, $content[0].'|'.$current .'');
fclose($handle);
}
}
}
}
Edit: My way to test the request time was with microtime and simulate 10'000 users. I ask google and tested (as example) http://technitip.net/simple-php-flood-protection-class
So I don't know what should be simple there? You have about 3 SQL Requests at one time like:
$this -> user_in_db($ip))
$this->user_flooding($ip);
$this->remove_old_users();
It maybe supply more functions, but all legit users use servertime for nothing. ;)
If you want to stop flooding a search page you can try it like this way:
$flood_protection_interval = 2;
session_start();
if(
isset($_SESSION['ip']) &&
$_SESSION['counter'] > 10 &&
$_SESSION['last_post'] + $flood_protection_interval > time()
){
// $_SESSION['counter'] = 0; // Use this if you want to reset counter
die("<pre>\n\n\n\t<b>FLOOD PROTECTION</b>");
}
$_SESSION['counter']++;
$_SESSION['last_post'] = time();
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
So if your visitor search 10 times under e.g. 2 seconds he will be stopped!
I thought about using sessions, like
have a session that contains a
timestamp that gets checked every time
they send data to like.php
This won't stop bots as they can receive and send the same cookies that users do.
You should really have users logging into such a system. Seems to be worth protecting access. You could also consider limiting posts per minute per ip but multiple bots could still send many spam messages.
If you don't want to implement a login then many sites use captcha to try and cut down on such attempts.
http://www.phpcaptcha.org/

Categories