I am using a simple script at the top of every page that will update a LastActive column in the database:
$username = $_SESSION['username'];
$userID = $_SESSION['user_id'];
if(isset($username, $userID)) {
if ($insert_stmt = $mysqli->prepare("UPDATE Users SET lastActive = DATE_ADD(Now(), interval 6 hour) WHERE username = ?")) {
$insert_stmt->bind_param('s', $username);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
$insert_stmt->close();
header('Location: ../headers/error.php?err=Failed Upload');
}
}
$insert_stmt->close();
}
I always want to keep performance and security in mind. Would this lead to poor performance in the future with 000's of connections?
How does using cookies (not that I know how) differ from a simple script like this?
Thanks
edit:
$username = $_SESSION['username'];
$userID = $_SESSION['user_id'];
$loginTime = $_SESSION['timestamp'];
date_default_timezone_set("Europe/London");
$now = new DateTime();
$diff=$now->diff($loginTime);
$minutes = $diff->format(%i);
if(isset($username, $userID) && $minutes> 30) {
$_SESSION['timestamp'] = $now;
$online = true;
}
Couple of suggestions:
You could do this via AJAX, so that the LastVisited is updated asynchronously after the user's page loads. That way, there won't be any impact to the page load time for the user.
If, for any reason, your SQL query fails, you should fail silently. Since recording Last Visited is not business critical, you should not redirect the user to an error page. Maybe just log an error, and set up an alert so if there are multiple failures, you get alerted and can take a look at it.
All that you made with cookies will be data supplied by your users, then you cannot trust it.
In other hand, if you work with cookies, all of them will travel in each request header.
You should do it in server side and yes, a database is not performant.
You can try to persist this information with something like Redis, a in-memory data structure store, used as database, cache and message broker.
I thought I'd post the way I got around this for any one else looking for a User Online type method. Of course this might have been done much better but works in my situation.
I am using both database entries and session to test if a user is online.
On user login I update a column in my users table with a Now() timestamp and add this to their session data.
At the top of each page I am running a script to check if the user is logged in and get their timestamp from session data. if this data is 45 minutes old, the script will update the table setting the lastActive column of my users table to Now();
<?php
include_once 'functions.php';
if(isset($_SESSION['username'], $_SESSION['user_id'], $_SESSION['lastActive'])) {
date_default_timezone_set("Europe/London");
$now = new DateTime();
$lastActive = $_SESSION['lastActive'];
$diff=$now->diff($lastActive);
$hours = $diff->format('%h');
$mins = $diff->format('%i');
$day = $diff->format('%d');
$month = $diff->format('%m');
$year = $diff->format('%y');
if($mins > 45 || $hours >= 1 || $day >= 1 || $month >= 1 || $year >= 1) {
$_SESSION['lastActive'] = $now;
set_last_active($mysqli, $_SESSION['username']);
}
}
set_latst_action is simply just:
function set_last_active($mysqli, $username) {
if ($stmt = $mysqli->prepare("UPDATE Users SET lastActive = Now() WHERE username = ?")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->close();
}
}
then when I want to see if a user is online for example on a profile page I call isOnline();
function isOnline($mysqli, $username) {
if ($stmt = $mysqli->prepare("SELECT lastActive FROM Users WHERE username = ? LIMIT 1")) {
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == 1) {
$stmt->bind_result($return);
$stmt->fetch();
$lastActive = $return;
} else {
// user does not exist
$lastActive = "";
return $lastActive;
$stmt->close();
}
} else {
// SELECT failed
$lastActive = "";
return $lastActive;
$stmt->close();
}
if (!empty($lastActive)) {
date_default_timezone_set("Europe/London");
$dateNow = new DateTime;
$lastActiveDate = new DateTime($lastActive);
$diff=$dateNow->diff($lastActiveDate);
$hours = $diff->format('%h');
$mins = $diff->format('%i');
$day = $diff->format('%d');
$month = $diff->format('%m');
$year = $diff->format('%y');
if ($mins > 45 || $hours >= 1 || $days >= 1 || $month >= 1 || $year >= 1) {
$return = "Offline";
return $return;
}
else {
$return = "Online";
return $return;
}
}
else {
$return = "Offline";
return $return;
}
}
Related
I want to block a someone who tried to login 4 times with a wrong password.
The problem is: When I use "modify" and change the timestamp with 15 minutes, I get -1 as output and after two minutes I get -2 as output. I tied for so long and I searched a lot on internet, but it still doesn't work.
How I want it to work:
In the database is the column: "falselog". If the username of the visiter is correct but the password is incorrect, falselog will be +1. When falselog is 4, the visiter will be banned for 15 minutes. So the visiter is able to try 4 times. After 15 minutes, the visiter can try again.
This is my object with all the code:
public function logUser($username, $password) {
// query id = 2
$sql2_1 = "SELECT
id,
password,
falselog,
lastlogin
FROM users
WHERE username ='".$username."' ";
$result2_1 = $this->con->query($sql2_1);
$fetch2_1 = mysqli_fetch_array($result2_1);
$count2_1 = $result2_1->num_rows;
$now = new DateTime('now');
$blockedSince = new DateTime($fetch2_1['lastlogin']);
$fout = $fetch2_1['falselog'];
$date_old = date ("Y-m-d H:i:s", strtotime("now"));
$block = date("i", $fetch2_1['lastlogin']) + 16;
$current = date("i", strtotime("now"));
$wait = $block - $current ;
$dbtime = date ("Y-m-d H:i:s", strtotime($date_old));
// This is the code that doesn't work
if ($fetch2_1['falselog']>=4 AND $blockedSince->modify('+15 minutes') > $now) {
$error[] = 'This account has been banned, try again about '.$wait.' minutes';
$decline = true;
$date_old = $fetch2_1['lastlogin'];
}
elseif (!preg_match("/^[A-Za-z0-9-]+$/", $username)) {
$error[] = 'De input bevat ongeldige tekens (alleen cijfers en letters toegestaan)';
}
elseif ($count2_1 === 0) {
$error[] = 'Wrong login data';
}
elseif ($fetch2_1['password']!=sha1($password)) {
$error[] = 'wrong password';
$fout = $fetch2_1['falselog']+1;
}
if ((count($error) == 0) OR ($fetch2_1['falselog']==4 AND $blockedSince->modify('+15 minutes') < $now)) {
$fout = 0;
}
$sql2_2 = "UPDATE users SET
falselog='".$fout."',
lastlogin='".$dbtime."'
WHERE username='".$username."' ";
if ($this->con->query($sql2_2) === TRUE) {
if (count($error) == 0) {
return false;
}
else {
return $error;
}
}
else {
echo "Error: " . $sql2_2 . "<br>" . $this->con->error;
return true;
}
}
You should check that here
$blockedSince = new DateTime($fetch2_1['lastlogin']);
you get the correct data for DateTime, try var_dump($blockedSince); after this line, and check that it has correct value inside;
try this
$blockedSince = mktime($fetch2_1['lastlogin']);
I have this weekly countdown process and if a login user reaches the 0 weeks limit his page will be banned from the site and that's fine, my problem is if i'm the admin i don't want this process to ban me.
On this platform i have user and admin privileges
like this: For admin: $user->isAdmin() and for the user : if($user->islg()
The Php process is this:
if($user->islg()) {
function get_weeks_remaining($date, $expire){
$difference = strtotime($expire) - strtotime($date);
return floor($difference / 604800);
}
$link = mysqli_connect("localhost", "user", "password", "table");
$nume = $user->data->username;
$id = $user->data->id;
$date = date('m/d/Y h:i:s a', time());
$expire_date = 'May 14, 2016';
$remain = get_weeks_remaining($date, $expire_date);
$reason = 'user has been suspended';
// weeks remaining
$save=mysql_query("INSERT INTO `week-ferify`(`id`,`date`,`name`,`expire`,`remain`)VALUES('$id','$date','$name','$expire_date','$remain')");
$sql = "SELECT `id`,`remain` FROM `week-ferify`";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while(list($id,$remain) = mysqli_fetch_array($result)){
if($remain > 0 and $remain < 2){
echo "<div class=\"week-remain-box\"><span class='week-remain-text'>week remain</span><p class='week-remain-remain'>$remain</p></div>";
}else{
echo "<div class=\"week-remain-box\"><span class='week-remain-text'>weeks remains</span><p class='week-remain-remain'>$remain</p></div>";
//Ban process
} if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
mysqli_free_result($result);
}
}
}
I don't know where to put $user->isAdmin() for not being banned by the process and only simple users to get banned. Thanks for any advice, and sorry for my bad english.
Given that the $user->isAdmin() method returns true or false based on whether the user is an administrator:
Place an if statement before the actual ban code.
//Ban process
if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
if(!$user->isAdmin()){
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
However, if you can safely assume that the default setting for banned is 0. I suggest you place wrap the condition over the entire "banning code"
//Ban process
if(!$user->isAdmin()){
if ($remain > 0 and $remain < 2) {
mysql_query("UPDATE `mls_users` SET banned=0 WHERE id=$id");
} else {
mysql_query("UPDATE `mls_users` SET banned=1 WHERE id=$id");
mysql_query("INSERT INTO `mls_banned`(`id`,`until`,`by`,`reason`)VALUES('$id','1462317824','1','$reason')");
}
}
And also you should probably modify the counter too.
A user will request a file by number via a URL like script.php?userid=222. This example would show the record of file #222.
Now I want to limit the number of files per (remote IP) user to a maximum of 5 different records in a minute. However, the user should be able to access the same id record any number of time.
So the user could access file #222 any number of times, but if the (remote IP) user accesses more than 5 other different records in a minute, then it should show an error.
For example, suppose within a minute the following requests are made:
script.php?userid=222
script.php?userid=523
script.php?userid=665
script.php?userid=852
script.php?userid=132
script.php?userid=002
then at the last request it should show the error message.
Here is the basic code:
$id = $_GET['userid'];
if (!isset($_GET['userid']) || empty($_GET['userid'])) {
echo "Please enter the userid";
die();
}
if (file_exists($userid.".txt") &&
(filemtime($userid.".txt") > (time() - 3600 * $ttime ))) {
$ffile = file_get_contents($userid.".txt");} else {
$dcurl = curl_init();
$ffile = fopen($userid.".txt", "w+");
curl_setopt($dcurl, CURLOPT_URL,"http://remoteserver.com/data/$userid");
curl_setopt($dcurl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($dcurl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($dcurl, CURLOPT_TIMEOUT, 50);
curl_setopt($dcurl, CURLOPT_FILE, $ffile);
$ffile = curl_exec($dcurl);
if(curl_errno($dcurl)) // check for execution errors
{
echo 'Script error: ' . curl_error($dcurl);
exit;
}
curl_close($dcurl);
$ffile = file_get_contents($userid.".txt");
}
Instead of relying on the IP address, you could use the session mechanism. You can create a session scope via session_start(), and then store information that sticks with the same user session.
I would then suggest to keep in this session scope the list of unique IDs used in previous requests that user made, together with the time of the request, ignoring any repeated requests, which are always allowed. As soon as this list contains 5 elements with a time stamp within the last minute and a new ID is requested, you show the error and refuse the lookup.
Here is the code that does this. You should place it right after you have checked the presence of the userid argument, and before the retrieval of the file contents:
// set the variables that define the limits:
$min_time = 60; // seconds
$max_requests = 5;
// Make sure we have a session scope
session_start();
// Create our requests array in session scope if it does not yet exist
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = [];
}
// Create a shortcut variable for this array (just for shorter & faster code)
$requests = &$_SESSION['requests'];
$countRecent = 0;
$repeat = false;
foreach($requests as $request) {
// See if the current request was made before
if ($request["userid"] == $id) {
$repeat = true;
}
// Count (only) new requests made in last minute
if ($request["time"] >= time() - $min_time) {
$countRecent++;
}
}
// Only if this is a new request...
if (!$repeat) {
// Check if limit is crossed.
// NB: Refused requests are not added to the log.
if ($countRecent >= $max_requests) {
die("Too many new ID requests in a short time");
}
// Add current request to the log.
$countRecent++;
$requests[] = ["time" => time(), "userid" => $id];
}
// Debugging code, can be removed later:
echo count($requests) . " unique ID requests, of which $countRecent in last minute.<br>";
// if execution gets here, then proceed with file content lookup as you have it.
Deleted session cookies...
Sessions are maintained by cookies on the client. The user may delete such cookies, an so get a new session, which would allow the user to make new requests without regard of what was previously requested.
One way to get around this is to introduce a cool-down period for each new session. For instance, you could have them wait for 10 seconds before a first request can be made. To do that, replace in above code:
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = [];
}
By:
$initial_delay = 10; // 10 seconds delay for new sessions
if (!isset($_SESSION['requests'])) {
$_SESSION['requests'] = array_fill(0, $max_requests,
["userid" => 0, "time" => time()-$min_time+$initial_delay]
);
}
This is of course less user friendly as it affects any new session, also of users who are not trying to cheat by deleting cookies.
Registration
The better way is to only allow the lookup services to registered users. For this you must provide a user database and authentication system (for example password based). The requests should be logged in the database, keyed by the user's ID. If then a new session starts, the user must first authenticate again, and once authenticated the request history is retrieved from the database. This way the user cannot cheat around it by changing something on their client configuration (IP address, cookies, employing multiple devices in parallel, ...)
<?php
// session_start();
// session_destroy();
// exit;
echo index();
function index()
{
$id = rand(000,020);
$min_time = 60;
$max_requests = 5;
// $id = 0;
session_start();
$repeat = false;
if(!isset($_SESSION["countRecent"]) && !isset($_SESSION["countRecent"]) && !isset($_SESSION["countRecent"])){
$_SESSION["countRecent"] = 1;
$_SESSION["time"] = time();
$_SESSION['userid'][] = $id;
}else{
if ($_SESSION["countRecent"] >= $max_requests) {
if(!in_array($id,$_SESSION['userid'])){
if ($_SESSION["time"] <= time() - $min_time) {
$_SESSION["countRecent"] = 1;
$_SESSION["time"] = time();
}else{
return("Too many requests in a short time wait ". ( $_SESSION["time"] - (time() - $min_time) )). " Seconds";
}
}
}else{
if(!in_array($id,$_SESSION['userid'])){
$_SESSION["countRecent"] = $_SESSION["countRecent"] + 1;
$_SESSION['userid'][] = $id;
}
}
}
return "Your Result goes here.. id: $id Counts: ". $_SESSION["countRecent"];
}
Try this. Fast , low memory usage
But not secure;
also use database
<?php
$conn = mysqli_connect("localhost", "root", "","db_name") or die("Could not connect database");
$id = rand(0,99);
// $id = 100;
echo index($id);
function index($id,$user=1,$ip='192.168.0.10',$max_requests = 5,$min_time = 20)
{
global $conn;
$time = time();
$req = "INSERT INTO `limit_api_by_ip2`(`id`, `ip`, `time`, `user`, `req`)
VALUES (null,INET_ATON('$ip'),'$time','$user',1)
ON DUPLICATE KEY UPDATE req=req+1;";
$req2 = "INSERT INTO `limit_api_by_ip2`(`id`, `ip`, `time`, `user`, `req`)
VALUES (null,INET_ATON('$ip'),'$time','$user',1)
ON DUPLICATE KEY UPDATE req=1,`time`='".time()."' ;";
$reqid = "INSERT INTO `limit_api_by_ip2_count`(`id`, `user`, `ids`) VALUES (null,'$user',$id)";
$getid = "SELECT `ids` FROM `limit_api_by_ip2_count` WHERE user = $user and ids = $id limit 1;";
$gettime = "SELECT `time`,`req` FROM `limit_api_by_ip2` WHERE user = $user and ip = INET_ATON('$ip') limit 1;";
// $id = 0;
$q = mysqli_query($conn,$getid);
$c = mysqli_num_rows($q);
if($c==0){
$get_time = mysqli_query($conn,$gettime);
$c1 = mysqli_num_rows($get_time);
if($c1==0){
mysqli_query($conn,$req);
mysqli_query($conn,$reqid);
}else{
$row = mysqli_fetch_row($get_time);
if ($row[1] >= $max_requests) {
if ($row[0] <= (time() - $min_time)) {
mysqli_query($conn,$req2);
mysqli_query($conn,$reqid);
}else{
return "Too many requests in a short time wait ".($row[0]-(time() - $min_time))." Seconds";
}
}else{
mysqli_query($conn,$req);
mysqli_query($conn,$reqid);
}
}
}else{
}
if(isset($row[1]))
{
$cc = "Counts: ".$row[1];
$dd = "new id: $id";
}else{
$cc = '';
$dd = "old id: $id";
}
return "Your Result goes here.. $dd ".$cc;
}
when I issue this code from a function, the cookies expire at the end of the session
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
However, executing the exact same code in a stand alone php file sets the cookies to expire on the correct date.
Here is the function
function validuser ($vid, $pwd){
global $pdo;
$stmnt = $pdo->prepare ("select * from members where vid = :vid and password = :password");
$stmnt->bindParam (':vid',$vid);
$stmnt->bindParam (':password', $pwd);
$stmnt->execute();
if ( $stmnt->rowCount() != 1){
header("Location:invalid.php");
break;
}
$member = $stmnt->fetch (PDO::FETCH_OBJ);
if ($member->nickname!="")
$_SESSION['user']= $member->nickname." ".$member->lname;
else
$_SESSION['user']= $member->fname." ".$member->lname;
$validuntil = '2024-02-17';
$validuntil = strtotime ($validuntil);
setcookie ('vid',$vid,$validuntil,'/');
setcookie ('pwd',$pwd,$validuntil,'/');
$_SESSION['ulot'] = $member->ulot;
$_SESSION['valid'] = '101150';
$_SESSION['admin'] = $member->admin == 1;
$_SESSION['vid'] = $member->vid;
$_SESSION['resid'] = $member->vid;
$_SESSION['pwd'] = $member->pwd;
$_SESSION['user'] = $member->fname." ".$member->lname;
header ("Location:mainmenu.php");
}
Can someone please explain this and how I fix it.
Thanks,
I'm writing a simple password-recovery function for the website I'm developing and I was wondering about the expire time.
Getting to the point, I want to add an expire time of around 48h for the reset password link I'm gonna send. Do I have to create a new column to store the current time and check it out some time later to see if its still valid, or is there a simpler way?
That's my code so far:
public function forgotPass($email) {
$bd = new Bd();
$conn = $bd->connect();
$stt = $conn->prepare("SELECT * FROM Users where email=?");
$stt-> bind_param("s",$email);
$stt-> execute();
$result = $stt->get_result();
if (mysqli_num_rows($result) == 1) {
$stt = $conn->prepare("INSERT INTO Users(recovery) VALUES(?)");
$recovery = $this->randHash(8);
if (!$recovery)
return false;
$stt-> bind_param("s",$recovery);
$stt-> execute();
}
}
and here's my randHash code:
private static function randHash($lenght) {
if (!filter_var($lenght, FILTER_VALIDATE_INT)) {
return false;
}
$allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$max = strlen($allowed) - 1;
for ($i=1;$i<=$lenght;$i++) {
$hash .= $allowed[mt_rand(0, $max)];
}
return $hash;
}
Just save the expiration time with the reset token in the database, and when the time has expired just don't accept the reset token anymore. This is by far the easiest and safest method.
Another way would be creating a reset hash, appending the time, and encrypting that with a secret key. Decrypt and check the timestamp when you check the hash. If the key leaked, however, this method becomes as weak as just putting it in plain text in the URL.
Storing the current date in database is one way to go. Then you can easily check if its less then 48 hours off. Another way to go is to include the time in the email.
public function forgotPass($email) {
$bd = new Bd();
$conn = $bd->connect();
$stt = $conn->prepare("SELECT * FROM Users where email=?");
$stt-> bind_param("s",$email);
$stt-> execute();
$result = $stt->get_result();
if (mysqli_num_rows($result) == 1) {
$hash1 = md5(microtime().$email.'xx'); //create a unique number for email
$ctime = time();
$hash2 = md5($hash1.$ctime); //create a unique hash based on hash1 and time
$stt = $conn->prepare("INSERT INTO Users(recovery) VALUES(?)");
$recovery = $hash2;
if (!$recovery)
return false;
$stt-> bind_param("s",$recovery);
$stt-> execute();
//send email with link
// http://www.example.com/resetpass.php?hash=$hash1&time=$ctime
}
}
//and then in resetpass.php
//NEEDS CHECKS FOR VALID QUERYVALUES
if (time()-$_GET['time'] <= 48 * 60 * 60) {
$checkhash = md5($_GET['hash'].$_GET['time']);
//check database for hash
}
EDIT: I received an email this morning regarding this answer and asking whether or not the hashing-part of my answer is just for making a really unique ID. The following is my response:
I went through and re-read the question on Stack Overflow. The code is not just for making a really unique ID (although it is important that there be no collisions). It is also to make it very hard for someone else to write their own password recovery link to gain access to a user account.
By creating a hash with a username and email (and without hashing the entire code), we would be able to include an additional validation on the user's identity. That is, merely having the link wouldn't be enough; a valid username and email address combination would also be needed to reset a password.
Strings are prepended to username, current time and email in a basic attempt to defeat rainbow tables. In retrospect, it would be better to replace the " " salts with base64_encode($row['username']) and base64_encode($email) respectively.
I would suggest creating two columns: recovery and recovery_expiry. Recovery_expiry holds when the link expires, and recovery holds the hash that must be compared. It consists of the username, a salt appended by the current time, and the current email address of the user.
function forgotPass($email)
{
$currTime = time();
$expiryTime = 60 * 60 * 24 * 2; // Two days
$bd = new Bd();
$conn = $bd->connect();
$stt = $conn->prepare("SELECT * FROM Users where email=?");
$stt->bind_param("s", $email);
$stt->execute();
$result = $stt->get_result();
if (mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array();
$stt = $conn->prepare("INSERT INTO Users(recovery, recovery_expiry)"
. " VALUES(?,?)");
$hash = hash("sha256", " " . $row['username'])
. hash("sha256", "vivid" . $currTime)
. hash("sha256", " " . $email);
$stt->bind_param("s", $hash);
$stt->bind_param("i", $currTime + $expiryTime);
$stt->execute();
}
else
{
// Return that the given email address did not match any records
}
// Here would be the logic to send the forgotten password link to the user
}
function checkHash($hash)
{
$row = null;
$currTime = time();
$bd = new Bd();
$conn = $bd->connect();
$stt = $conn->prepare("SELECT * FROM Users WHERE recovery=? AND recovery_expiry < $currTime");
$stt->bind_param("s", $hash);
$stt->execute();
$result = $stt->get_result();
if (mysqli_num_rows($result) == 1)
{
$row = mysqli_fetch_array();
}
return $row;
}