Related
What I want to do is to have a variable that increments by 1 after every reload. Now, I can't do cookies because I want it to increment globally, and I've tried sessions but I had no luck with them. If anyone could help me out I'd really appreciate it. I actually can't give any code samples because my tries have turned out very messy.
If you want a variable for each user, then I would definitely go with sessions :
<?php
session_start();
if (!isset($_SESSION['counter'])) {
$_SESSION['counter'] = 0;
} else {
$_SESSION['counter']++;
}
However if you want a unique variable that increases at each load (i.e the same for all users), then you could use a file to store the number of views :
<?php
if(file_exists('counter.txt'))
{
$counter_f = fopen('counter.txt', 'r+');
$count = fgets($counter_f);
}
else
{
$counter_f = fopen('counter.txt', 'a+');
$count = 0;
}
$count++;
fseek($counter_f, 0);
fputs($counter_f, $count);
fclose($counter_f);
?>
I've placed a hit counter on my page. It reads a text file, increments the number in the file, and later in the page, I output the incremented value.
$hitsFile = "hits/exps/stats.txt";
$hits = file($hitsFile);
$hits[0]++;
$fp = fopen($hitsFile , "w");
flock($fh, LOCK_EX);
fwrite($fp , $hits[0]);
fclose($fp);
My problem is that if I reload the page, the code will increment the hits. I don't want that. I thought of using session to fix that, but with session, in order the increment the hits again, I need to exit the site and visit again. I don't want that either.
I want it to increment not when I reload the page but when I revisit the page.
For example, let's say I have two-page website, Home and Contact, and on contact page I have a hit counter. I don't want the hit counter to increment if I reload(refresh) the contact page, but if I leave the contact page and visit homepage, and later revisit the contact page, I want it to increment.
In short, I don't want it to increment on page reload. Is there a way to do that?
In each of your pages, you need to write the page name in the session.
Do something like this:
$_SESSION['page'] = 'contact';
On the pages where you need to count hits, you need to check this session key.
For example, if you were on page 'contact', then $_SESSION['page'] == 'contact'.
Now when you go to visit the 'homepage':
$page = $_SESSION['page'];
if($page != 'homepage')
{
//increment your hits counter
$_SESSION['page'] = 'homepage';
}
I suggest this method, is my preferred, create in root these folders: cnt and log... then put inside cnt folder the following files cnt.php and showcnt.php...
cnt.php
<?php
##############################################################################
# Php Counter With Advanced Technology For The Prevention Of Reloading Pages #
# Version: 1.4 - Date: 13.11.2014 - Created By Alessandro Marinuzzi [Alecos] #
##############################################################################
function cnt($file) {
session_start();
global $pagecnt;
$reloaded = isset($_SERVER['HTTP_CACHE_CONTROL']) && $_SERVER['HTTP_CACHE_CONTROL'] === 'max-age=0';
$thispage = basename($_SERVER['SCRIPT_FILENAME']);
if (!isset($_SESSION['first_go'])) {
$_SESSION['first_go'] = 1;
$first_go = TRUE;
} else {
$first_go = FALSE;
}
if (!isset($_SESSION['thispage'])) {
$_SESSION['thispage'] = $thispage;
}
if ($_SESSION['thispage'] != $thispage) {
$_SESSION['thispage'] = $thispage;
$new_page = TRUE;
} else {
$new_page = FALSE;
}
$pagecnt = rtrim(file_get_contents($file));
if ((!$reloaded) && ($new_page == TRUE) || ($first_go == TRUE)) {
$fd = fopen($file, 'w+');
flock($fd, LOCK_EX);
fwrite($fd, ++$pagecnt);
flock($fd, LOCK_UN);
fclose($fd);
}
}
?>
showcnt.php
<?php
##############################################################################
# Show Counter Results - v.1.4 - 13.11.2014 By Alessandro Marinuzzi [Alecos] #
##############################################################################
function gfxcnt($file) {
global $number;
$number = rtrim(file_get_contents($file));
$lenght = strlen($number);
$gfxcnt = "";
for ($i = 0; $i < $lenght; $i++) {
$gfxcnt .= $number[$i];
}
$gfxind = "<span class=\"counter\"><span class=\"number\">$gfxcnt</span></span>";
echo $gfxind;
}
?>
Well, then edit your index.php or other php page... and put at the beginning this piece of code:
<?php session_start(); include("cnt/cnt.php"); cnt("log/index.txt"); include("cnt/showcnt.php"); ?>
Well, then edit index.php or other php page... and use this piece of code for reading counter file:
<?php gfxcnt("log/index.txt"); ?>
It's all, I hope you'll find my answer useful :) My counter can write/read multiple php pages...
Source: my blog (https://www.alecos.it/new/101/101.php)
Add session_start(); to the top.
Now change your if to this:
if (!isset($_SESSION['lastpage']) || $_SESSION['lastpage'] != $_SERVER['QUERY_STRING') {
$hits[0]++;
}
$_SESSION['lastpage'] = $_SERVER['QUERY_STRING'];
This will basically force someone to move to another page if they want to increment the counter.
Update the hit count only if the current URL is not stored in $_SESSION['url'].
After updating the hit count, store the current URL in $_SESSION['url'].
I need to keep a session alive for 30 minutes and then destroy it.
You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that.
First:
session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.
But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.
Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.
Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:
Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.
So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.
And second:
session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]
Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.
Conclusion / best solution:
The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
Notes:
session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.
Simple way of PHP session expiry in 30 minutes.
Note : if you want to change the time, just change the 30 with your desired time and do not change * 60: this will gives the minutes.
In minutes : (30 * 60)
In days : (n * 24 * 60 * 60 ) n = no of days
Login.php
<?php
session_start();
?>
<html>
<form name="form1" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="text"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" value="SignIn" name="submit"></td>
</tr>
</table>
</form>
</html>
<?php
if (isset($_POST['submit'])) {
$v1 = "FirstUser";
$v2 = "MyPassword";
$v3 = $_POST['text'];
$v4 = $_POST['pwd'];
if ($v1 == $v3 && $v2 == $v4) {
$_SESSION['luser'] = $v1;
$_SESSION['start'] = time(); // Taking now logged in time.
// Ending a session in 30 minutes from the starting time.
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
header('Location: http://localhost/somefolder/homepage.php');
} else {
echo "Please enter the username or password again!";
}
}
?>
HomePage.php
<?php
session_start();
if (!isset($_SESSION['luser'])) {
echo "Please Login again";
echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
}
else {
$now = time(); // Checking the time now when home page starts.
if ($now > $_SESSION['expire']) {
session_destroy();
echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
}
else { //Starting this else one [else1]
?>
<!-- From here all HTML coding can be done -->
<html>
Welcome
<?php
echo $_SESSION['luser'];
echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
?>
</html>
<?php
}
}
?>
LogOut.php
<?php
session_start();
session_destroy();
header('Location: http://localhost/somefolder/login.php');
?>
Is this to log the user out after a set time? Setting the session creation time (or an expiry time) when it is registered, and then checking that on each page load could handle that.
E.g.:
$_SESSION['example'] = array('foo' => 'bar', 'registered' => time());
// later
if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
unset($_SESSION['example']);
}
Edit: I've got a feeling you mean something else though.
You can scrap sessions after a certain lifespan by using the session.gc_maxlifetime ini setting:
Edit:
ini_set('session.gc_maxlifetime', 60*30);
This post shows a couple of ways of controlling the session timeout: http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
IMHO the second option is a nice solution:
<?php
/***
* Starts a session with a specific timeout and a specific GC probability.
* #param int $timeout The number of seconds until it should time out.
* #param int $probability The probablity, in int percentage, that the garbage
* collection routine will be triggered right now.
* #param strint $cookie_domain The domain path for the cookie.
*/
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
// Change the save path. Sessions stored in teh same path
// all share the same lifetime; the lowest lifetime will be
// used for all. Therefore, for this to work, the session
// must be stored in a directory where only sessions sharing
// it's lifetime are. Best to just dynamically create on.
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start();
// Renew the time left until this session times out.
// If you skip this, the session will time out based
// on the time when it was created, rather than when
// it was last used.
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
Well i understand the aboves answers are correct but they are on application level, why don't we simply use .htaccess file to set the expire time ?
<IfModule mod_php5.c>
#Session timeout
php_value session.cookie_lifetime 1800
php_value session.gc_maxlifetime 1800
</IfModule>
Use the session_set_cookie_params function to do this.
It is necessary to call this function before the session_start() call.
Try this:
$lifetime = strtotime('+30 minutes', 0);
session_set_cookie_params($lifetime);
session_start();
See more in: http://php.net/manual/function.session-set-cookie-params.php
if (isSet($_SESSION['started'])){
if((mktime() - $_SESSION['started'] - 60*30) > 0){
//Logout, destroy session, etc.
}
}
else {
$_SESSION['started'] = mktime();
}
It's actually easy with a function like the following. It uses database table name 'sessions' with fields 'id' and 'time'.
Every time when the user visits your site or service again you should invoke this function to check if its return value is TRUE. If it's FALSE the user has expired and the session will be destroyed (Note: This function uses a database class to connect and query the database, of course you could also do it inside your function or something like that):
function session_timeout_ok() {
global $db;
$timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
$ok = false;
$session_id = session_id();
$sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
$rows = $db->query($sql);
if ($rows === false) {
//Timestamp could not be read
$ok = FALSE;
}
else {
//Timestamp was read succesfully
if (count($rows) > 0) {
$zeile = $rows[0];
$time_past = $zeile['time'];
if ( $timeout + $time_past < time() ) {
//Time has expired
session_destroy();
$sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
$affected = $db -> query($sql);
$ok = FALSE;
}
else {
//Time is okay
$ok = TRUE;
$sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
$erg = $db -> query($sql);
if ($erg == false) {
//DB error
}
}
}
else {
//Session is new, write it to database table sessions
$sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
$res = $db->query($sql);
if ($res === FALSE) {
//Database error
$ok = false;
}
$ok = true;
}
return $ok;
}
return $ok;
}
Store a timestamp in the session
<?php
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('db_connection.php');
// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $user;
$_SESSION['login_time'] = time();
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
header("Location:login.php");
}
else
{
// uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
//$_SESSION['login_time'] = time();
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all other content
}
?>
Please use following block of code in your include file which loaded in every pages.
$expiry = 1800 ;//session expiry required after 30 mins
if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
session_unset();
session_destroy();
}
$_SESSION['LAST'] = time();
This was an eye-opener for me, what Christopher Kramer wrote in 2014 on
https://www.php.net/manual/en/session.configuration.php#115842
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). [...]
How PHP handles sessions is quite confusing for beginners to understand. This might help them by giving an overview of how sessions work:
how sessions work(custom-session-handlers)
Use this class for 30 min
class Session{
public static function init(){
ini_set('session.gc_maxlifetime', 1800) ;
session_start();
}
public static function set($key, $val){
$_SESSION[$key] =$val;
}
public static function get($key){
if(isset($_SESSION[$key])){
return $_SESSION[$key];
} else{
return false;
}
}
public static function checkSession(){
self::init();
if(self::get("adminlogin")==false){
self::destroy();
header("Location:login.php");
}
}
public static function checkLogin(){
self::init();
if(self::get("adminlogin")==true){
header("Location:index.php");
}
}
public static function destroy(){
session_destroy();
header("Location:login.php");
}
}
Using timestamp...
<?php
if (!isset($_SESSION)) {
$session = session_start();
}
if ($session && !isset($_SESSION['login_time'])) {
if ($session == 1) {
$_SESSION['login_time']=time();
echo "Login :".$_SESSION['login_time'];
echo "<br>";
$_SESSION['idle_time']=$_SESSION['login_time']+20;
echo "Session Idle :".$_SESSION['idle_time'];
echo "<br>";
} else{
$_SESSION['login_time']="";
}
} else {
if (time()>$_SESSION['idle_time']){
echo "Session Idle :".$_SESSION['idle_time'];
echo "<br>";
echo "Current :".time();
echo "<br>";
echo "Session Time Out";
session_destroy();
session_unset();
} else {
echo "Logged In<br>";
}
}
?>
I have used 20 seconds to expire the session using timestamp.
If you need 30 min add 1800 (30 min in seconds)...
You can straight use a DB to do it as an alternative. I use a DB function to do it that I call chk_lgn.
Check login checks to see if they are logged in or not and, in doing so, it sets the date time stamp of the check as last active in the user's db row/column.
I also do the time check there. This works for me for the moment as I use this function for every page.
P.S. No one I had seen had suggested a pure DB solution.
Here you can set the hours
$lifespan = 1800;
ini_set('session.gc_maxlifetime', $lifespan); //default life time
Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.
<?php
if (!isset($_SESSION)) {
session_start();
}
// anti flood protection
if($_SESSION['last_session_request'] > time() - 2){
// users will be redirected to this page if it makes requests faster than 2 seconds
header("location: http://www.example.com/403.html");
exit;
}
$_SESSION['last_session_request'] = time();
?>
I've already tested this script as you higher the second It Will keep redirecting to http://www.example.com/403.html without any reason.
Can anyone tell me why?
Let's think about this logically for a second...
The attacker's request is already being sent to the web-server and through to the PHP script.
The bottle-neck which causes failure in DDoS attacks is the web-server.
The idea behind a DDoS attack is just that - to cause a denial of service, in which the website/server is unable to process any new requests. So in escense, this approach is irrational.
You need to go up the ladder of request handling.
If you have a server to your disposal, it's easier. You could simply implement a rate limiting rule on the kernel firewall/iptables.
But assuming you do not have access to that, Apache is still at your disposal - although not as efficient.
Implementing a rule within .htaccess is a better solution, but still not perfect.
But depending on the DDoS attack, there's no real solution at the developer's disposal to block it.
I'm using a good anti-flood script that des not need cookies (perfect for webservices). It's not perfect against advanced DDOS attacks but it's enough for preventing beginners attacks and automatic multiple requests.
For using it, before it's needed to create "flood" folder with a "ctrl" file inside and a "lock" subfolder. Also needed to be setted with correct permissions.
Already tested by me.
define("SCRIPT_ROOT", dirname(__FILE__));
// number of allowed page requests for the user
define("CONTROL_MAX_REQUESTS", 3);
// time interval to start counting page requests (seconds)
define("CONTROL_REQ_TIMEOUT", 2);
// seconds to punish the user who has exceeded in doing requests
define("CONTROL_BAN_TIME", 5);
// writable directory to keep script data
define("SCRIPT_TMP_DIR", SCRIPT_ROOT."/flood");
// you don't need to edit below this line
define("USER_IP", $_SERVER["REMOTE_ADDR"]);
define("CONTROL_DB", SCRIPT_TMP_DIR."/ctrl");
define("CONTROL_LOCK_DIR", SCRIPT_TMP_DIR."/lock");
define("CONTROL_LOCK_FILE", CONTROL_LOCK_DIR."/".md5(USER_IP));
#mkdir(CONTROL_LOCK_DIR);
#mkdir(SCRIPT_TMP_DIR);
if (file_exists(CONTROL_LOCK_FILE)) {
if (time()-filemtime(CONTROL_LOCK_FILE) > CONTROL_BAN_TIME) {
// this user has complete his punishment
unlink(CONTROL_LOCK_FILE);
} else {
// too many requests
echo "<h1>DENIED</h1>";
echo "Please try later.";
touch(CONTROL_LOCK_FILE);
die;
}
}
function antiflood_countaccess() {
// counting requests and last access time
$control = Array();
if (file_exists(CONTROL_DB)) {
$fh = fopen(CONTROL_DB, "r");
$control = array_merge($control, unserialize(fread($fh, filesize(CONTROL_DB))));
fclose($fh);
}
if (isset($control[USER_IP])) {
if (time()-$control[USER_IP]["t"] < CONTROL_REQ_TIMEOUT) {
$control[USER_IP]["c"]++;
} else {
$control[USER_IP]["c"] = 1;
}
} else {
$control[USER_IP]["c"] = 1;
}
$control[USER_IP]["t"] = time();
if ($control[USER_IP]["c"] >= CONTROL_MAX_REQUESTS) {
// this user did too many requests within a very short period of time
$fh = fopen(CONTROL_LOCK_FILE, "w");
fwrite($fh, USER_IP);
fclose($fh);
}
// writing updated control table
$fh = fopen(CONTROL_DB, "w");
fwrite($fh, serialize($control));
fclose($fh);
}
Taken from here: https://github.com/damog/planetalinux/blob/master/www/principal/suscripcion/lib/antiflood.hack.php
just change > to <:
<?php
if (!isset($_SESSION)) {
session_start();
}
// anti flood protection
if($_SESSION['last_session_request'] < time() - 2){
// users will be redirected to this page if it makes requests faster than 2 seconds
header("location: http://www.example.com/403.html");
exit;
}
$_SESSION['last_session_request'] = time();
?>
What spudinksi said still holds true, however here is what your looking for:
<?php
if (!isset($_SESSION)) {
session_start();
}
if($_SESSION['last_session_request'] > (time() - 5)){
if(empty($_SESSION['last_request_count'])){
$_SESSION['last_request_count'] = 1;
}elseif($_SESSION['last_request_count'] < 5){
$_SESSION['last_request_count'] = $_SESSION['last_request_count'] + 1;
}elseif($_SESSION['last_request_count'] >= 5){
header("location: http://www.example.com/403.html");
exit;
}
}else{
$_SESSION['last_request_count'] = 1;
}
$_SESSION['last_session_request'] = time();
?>
For stop DDos add a null route for that ip, like this:
route add -host ???.???.???.??? reject
There is a script called IOSec, which is quite old, but it might help.
This will count page reloads & also save time after 3 seconds ....
if it gives problems or to easy for newbies to bypass then leave comment..
if(empty($_SESSION['AFsys_time']) || $_SESSION['AFsys_time'] == '0') {
$tGoal = time() + 3; // Pluss Seconds
$_SESSION['AFsys_time'] = $tGoal;
}
if(empty($_SESSION['AFsys_pReloads']) || $_SESSION['AFsys_pReloads'] == 0 ) { $_SESSION['AFsys_pReloads'] = 1; } else { $_SESSION['AFsys_pReloads']++; };
if($_SESSION['AFsys_time'] < time()){
$_SESSION['AFsys_time'] = 0; // Session Reset
$_SESSION['AFsys_pReloads'] = 0; // Session Reset
}
if($_SESSION['AFsys_pReloads'] > '5' && $_SESSION['AFsys_time'] > time()){
$_SESSION['AFsys_time'] = 0; // Session Reset
$_SESSION['AFsys_pReloads'] = 0; // Session Reset
header("location: http://www.example.com/403.html");
exit;
}
this code not work for curl looping like this. session will create again on every curl exec;
for ($i=0;$i<999999999999999;$i++){
/**/
$c=curl_init();
curl_setopt($c,CURLOPT_URL,"URL YOU WANT ATTACK");
curl_setopt($c,CURLOPT_DNS_USE_GLOBAL_CACHE,TRUE);//dns
curl_setopt($c,CURLOPT_HEADER,0);//get the header
curl_setopt($c,CURLOPT_CONNECTTIMEOUT ,10);//get the header
curl_setopt($c,CURLOPT_NOBODY,0);//and *only* get the header
curl_setopt($c,CURLOPT_RETURNTRANSFER,1);//get the response as a string from curl_exec(), rather than echoing it
curl_setopt($c,CURLOPT_FRESH_CONNECT,1);//don't use a cached version of the url
curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:11.0) Gecko Firefox/11.0');
curl_setopt($c, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded;charset=UTF-8' ));
echo "\n $i";
}
Session may be not work, because we haven't session coockie.
I recommend such
$load = sys_getloadavg();
if ($load[0] > 20) {
header('HTTP/1.1 503 Too busy, try again later');
die('Server too busy. Please try again later.');
}
Or you can
shell_exec('/sbin/iptables -I INPUT -j DROP -s ' . $ip);
for ddosing $ip
I need to keep a session alive for 30 minutes and then destroy it.
You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that.
First:
session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.
But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.
Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.
Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:
Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.
So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.
And second:
session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]
Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.
Conclusion / best solution:
The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.
You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:
if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}
Notes:
session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.
Simple way of PHP session expiry in 30 minutes.
Note : if you want to change the time, just change the 30 with your desired time and do not change * 60: this will gives the minutes.
In minutes : (30 * 60)
In days : (n * 24 * 60 * 60 ) n = no of days
Login.php
<?php
session_start();
?>
<html>
<form name="form1" method="post">
<table>
<tr>
<td>Username</td>
<td><input type="text" name="text"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"></td>
</tr>
<tr>
<td><input type="submit" value="SignIn" name="submit"></td>
</tr>
</table>
</form>
</html>
<?php
if (isset($_POST['submit'])) {
$v1 = "FirstUser";
$v2 = "MyPassword";
$v3 = $_POST['text'];
$v4 = $_POST['pwd'];
if ($v1 == $v3 && $v2 == $v4) {
$_SESSION['luser'] = $v1;
$_SESSION['start'] = time(); // Taking now logged in time.
// Ending a session in 30 minutes from the starting time.
$_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
header('Location: http://localhost/somefolder/homepage.php');
} else {
echo "Please enter the username or password again!";
}
}
?>
HomePage.php
<?php
session_start();
if (!isset($_SESSION['luser'])) {
echo "Please Login again";
echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
}
else {
$now = time(); // Checking the time now when home page starts.
if ($now > $_SESSION['expire']) {
session_destroy();
echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
}
else { //Starting this else one [else1]
?>
<!-- From here all HTML coding can be done -->
<html>
Welcome
<?php
echo $_SESSION['luser'];
echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
?>
</html>
<?php
}
}
?>
LogOut.php
<?php
session_start();
session_destroy();
header('Location: http://localhost/somefolder/login.php');
?>
Is this to log the user out after a set time? Setting the session creation time (or an expiry time) when it is registered, and then checking that on each page load could handle that.
E.g.:
$_SESSION['example'] = array('foo' => 'bar', 'registered' => time());
// later
if ((time() - $_SESSION['example']['registered']) > (60 * 30)) {
unset($_SESSION['example']);
}
Edit: I've got a feeling you mean something else though.
You can scrap sessions after a certain lifespan by using the session.gc_maxlifetime ini setting:
Edit:
ini_set('session.gc_maxlifetime', 60*30);
This post shows a couple of ways of controlling the session timeout: http://bytes.com/topic/php/insights/889606-setting-timeout-php-sessions
IMHO the second option is a nice solution:
<?php
/***
* Starts a session with a specific timeout and a specific GC probability.
* #param int $timeout The number of seconds until it should time out.
* #param int $probability The probablity, in int percentage, that the garbage
* collection routine will be triggered right now.
* #param strint $cookie_domain The domain path for the cookie.
*/
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
// Set the max lifetime
ini_set("session.gc_maxlifetime", $timeout);
// Set the session cookie to timout
ini_set("session.cookie_lifetime", $timeout);
// Change the save path. Sessions stored in teh same path
// all share the same lifetime; the lowest lifetime will be
// used for all. Therefore, for this to work, the session
// must be stored in a directory where only sessions sharing
// it's lifetime are. Best to just dynamically create on.
$seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
$path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
if(!file_exists($path)) {
if(!mkdir($path, 600)) {
trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
}
}
ini_set("session.save_path", $path);
// Set the chance to trigger the garbage collection.
ini_set("session.gc_probability", $probability);
ini_set("session.gc_divisor", 100); // Should always be 100
// Start the session!
session_start();
// Renew the time left until this session times out.
// If you skip this, the session will time out based
// on the time when it was created, rather than when
// it was last used.
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
}
}
Well i understand the aboves answers are correct but they are on application level, why don't we simply use .htaccess file to set the expire time ?
<IfModule mod_php5.c>
#Session timeout
php_value session.cookie_lifetime 1800
php_value session.gc_maxlifetime 1800
</IfModule>
Use the session_set_cookie_params function to do this.
It is necessary to call this function before the session_start() call.
Try this:
$lifetime = strtotime('+30 minutes', 0);
session_set_cookie_params($lifetime);
session_start();
See more in: http://php.net/manual/function.session-set-cookie-params.php
if (isSet($_SESSION['started'])){
if((mktime() - $_SESSION['started'] - 60*30) > 0){
//Logout, destroy session, etc.
}
}
else {
$_SESSION['started'] = mktime();
}
It's actually easy with a function like the following. It uses database table name 'sessions' with fields 'id' and 'time'.
Every time when the user visits your site or service again you should invoke this function to check if its return value is TRUE. If it's FALSE the user has expired and the session will be destroyed (Note: This function uses a database class to connect and query the database, of course you could also do it inside your function or something like that):
function session_timeout_ok() {
global $db;
$timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
$ok = false;
$session_id = session_id();
$sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
$rows = $db->query($sql);
if ($rows === false) {
//Timestamp could not be read
$ok = FALSE;
}
else {
//Timestamp was read succesfully
if (count($rows) > 0) {
$zeile = $rows[0];
$time_past = $zeile['time'];
if ( $timeout + $time_past < time() ) {
//Time has expired
session_destroy();
$sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
$affected = $db -> query($sql);
$ok = FALSE;
}
else {
//Time is okay
$ok = TRUE;
$sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
$erg = $db -> query($sql);
if ($erg == false) {
//DB error
}
}
}
else {
//Session is new, write it to database table sessions
$sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
$res = $db->query($sql);
if ($res === FALSE) {
//Database error
$ok = false;
}
$ok = true;
}
return $ok;
}
return $ok;
}
Store a timestamp in the session
<?php
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];
require ('db_connection.php');
// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));
if( mysql_num_rows( $result ) > 0)
{
$array = mysql_fetch_assoc($result);
session_start();
$_SESSION['user_id'] = $user;
$_SESSION['login_time'] = time();
header("Location:loggedin.php");
}
else
{
header("Location:login.php");
}
?>
Now, Check if the timestamp is within the allowed time window (1800 seconds is 30 minutes)
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
header("Location:login.php");
}
else
{
// uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
//$_SESSION['login_time'] = time();
echo ( "this session is ". $_SESSION['user_id'] );
//show rest of the page and all other content
}
?>
Please use following block of code in your include file which loaded in every pages.
$expiry = 1800 ;//session expiry required after 30 mins
if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
session_unset();
session_destroy();
}
$_SESSION['LAST'] = time();
This was an eye-opener for me, what Christopher Kramer wrote in 2014 on
https://www.php.net/manual/en/session.configuration.php#115842
On debian (based) systems, changing session.gc_maxlifetime at runtime has no real effect. Debian disables PHP's own garbage collector by setting session.gc_probability=0. Instead it has a cronjob running every 30 minutes (see /etc/cron.d/php5) that cleans up old sessions. This cronjob basically looks into your php.ini and uses the value of session.gc_maxlifetime there to decide which sessions to clean (see /usr/lib/php5/maxlifetime). [...]
How PHP handles sessions is quite confusing for beginners to understand. This might help them by giving an overview of how sessions work:
how sessions work(custom-session-handlers)
Use this class for 30 min
class Session{
public static function init(){
ini_set('session.gc_maxlifetime', 1800) ;
session_start();
}
public static function set($key, $val){
$_SESSION[$key] =$val;
}
public static function get($key){
if(isset($_SESSION[$key])){
return $_SESSION[$key];
} else{
return false;
}
}
public static function checkSession(){
self::init();
if(self::get("adminlogin")==false){
self::destroy();
header("Location:login.php");
}
}
public static function checkLogin(){
self::init();
if(self::get("adminlogin")==true){
header("Location:index.php");
}
}
public static function destroy(){
session_destroy();
header("Location:login.php");
}
}
Using timestamp...
<?php
if (!isset($_SESSION)) {
$session = session_start();
}
if ($session && !isset($_SESSION['login_time'])) {
if ($session == 1) {
$_SESSION['login_time']=time();
echo "Login :".$_SESSION['login_time'];
echo "<br>";
$_SESSION['idle_time']=$_SESSION['login_time']+20;
echo "Session Idle :".$_SESSION['idle_time'];
echo "<br>";
} else{
$_SESSION['login_time']="";
}
} else {
if (time()>$_SESSION['idle_time']){
echo "Session Idle :".$_SESSION['idle_time'];
echo "<br>";
echo "Current :".time();
echo "<br>";
echo "Session Time Out";
session_destroy();
session_unset();
} else {
echo "Logged In<br>";
}
}
?>
I have used 20 seconds to expire the session using timestamp.
If you need 30 min add 1800 (30 min in seconds)...
You can straight use a DB to do it as an alternative. I use a DB function to do it that I call chk_lgn.
Check login checks to see if they are logged in or not and, in doing so, it sets the date time stamp of the check as last active in the user's db row/column.
I also do the time check there. This works for me for the moment as I use this function for every page.
P.S. No one I had seen had suggested a pure DB solution.
Here you can set the hours
$lifespan = 1800;
ini_set('session.gc_maxlifetime', $lifespan); //default life time
Just Store the current time and If it exceeds 30 minutes by comparing then destroy the current session.