Monday, April 30, 2012

Handling sessions with procedural PHP

I would like to dedicate this page to handling sessions using procedural php.



I'll begin with how I start most of my projects:



session_name('Easy_App');
session_start();

if (!isset( $_SESSION['ip'] )){
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
}

if (!isset( $_SESSION['created'] )){
$_SESSION['created'] = time();
}

if (!isset( $_SESSION['overall_views'] )){
$_SESSION['overall_views'] = 1;
}
else {
$_SESSION['overall_views']++;
}

if (!isset( $_SESSION['username'] )){
$_SESSION['username'] = "";
}

if (!isset( $_SESSION['logged_in'] )){
$_SESSION['logged_in'] = 0;
}

/*A quick method to keep pageviews to < 5 pages per 1 second per session*/
if (!isset($_SESSION['first_action'])){
$_SESSION['first_action'] = time();
}

$first_action = $_SESSION['first_action'];
if (!isset( $_SESSION['action'] )){
$_SESSION['action'] = 1;
}
else{
$_SESSION['action']++;
}

$action=$_SESSION['action'];
if ($action>=5){
unset($_SESSION['action']);
unset($_SESSION['first_action']);
if((time() - $first_action) <=1){
exit("Please Don't Hammer My Site ");
}
}


So We have a starting point:




  1. The Start of a session with a few regularly used parameters

  2. In the last few lines, prevention of hammering by casual users.



My question is this:



Where would you go from here? Improvements of the above code or a brief snippet of how you handle sessions using procedural php would be greatly appreciated.





No comments:

Post a Comment