Php/Mysql process with user & admin privilege issue - php

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.

Related

Php login script with login attemp

How can i limit the failed logins with this script? If the login fails, i insert it into the sql. (Is it the right way?)
But how can i check at the next login, that the user can now log in? I would take the login limit in 1 hour.
Aniway, is this code is good for that?
<?php
$loginError = array();
if(isset($_POST['login_submit']))
{
if(empty($_POST['email']) or !isset($_POST['email'])){$loginError[] = "Hiányzó email cím.";}
if(empty($_POST['pass']) or !isset($_POST['pass'])){$loginError[] = "Hiányzó jelszó.";}
if(strlen($_POST['email']) > 50 ){$loginError[] = "Hibás adat az email mezőben.";}
if(strlen($_POST['pass']) > 40 ){$loginError[] = "Hibás adat a jelszó mezőben.";}
if(count($loginError) == 0 )
{
$email = mysqli_real_escape_string($kapcs,$_POST['email']);
$pass = sha1($_POST['pass']);
$lekerdezes = mysqli_query($kapcs, "SELECT * FROM admin_user WHERE email = '$email'") or die(mysqli_error($kapcs));
if(mysqli_num_rows($lekerdezes) > 0 )
{
$adat = mysqli_fetch_assoc($lekerdezes);
if($adat['status'] == 1 )
{
if($adat['pass'] == $pass)
{
$_SESSION['adatok'] = $adat;
$_SESSION['email'] = $adat['email'];
$_SESSION['userid'] = $adat['id'];
header("Location:home.php");
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Még nincs aktiválva a fiók.";
}
}
else
{
$sql = "INSERT INTO loginattempts(log_address, log_datetime) VALUES ('".$_SERVER['REMOTE_ADDR']."', NOW())";
$insert_login_attempt = mysqli_query($kapcs, $sql) or die(mysqli_error($kapcs));
$loginError[] = "Hibás email cím vagy jelszó.";
}
}
}
?>
I would create a field in the database called status (blocked/ok) and assuming youve got a field timestamp for the last login...
Then Id connect to the database in case the login fails and save the status bloqued and the time stamp. the next attempt you would check the time.now vs last access...
I good suggestion would be create a function for the database connection so you can call it a couple of time without repeat the code, also dont forget use the try/except fot the db connection.

Last online php

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;
}
}

retrieve data from database that is updated

I've already made calculation for BMI and I can update height(will update weight soon) if user getting taller or shorter. The problem is, after I already update the height I cannot update BMI and BMI STATUS(underweight, normal, obese) which is a big problem for me..
This is my coding for php
if(!isset($_SESSION['user']))
{
header("Location: PHOME.php");
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
$userRow=mysql_fetch_array($res);
if(isset($_POST['updateH']))
{
$height = $_POST['height'];
$weight = $_SESSION['user'];
$sex = $_SESSION['user'];
$bmiresult = $_SESSION['user'];
$bmi = $weight/(($height/100)*($height/100));
if ($sex=="female")
{
if ($bmi <= 19)
$bmiresult="underweight!";
else if ($bmi>19 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
else if ($sex=="male")
{
if ($bmi <= 20)
$bmiresult="underweight!";
else if ($bmi>20 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
$sql = "UPDATE users SET height = $height, weight = $weight,
bmi = $bmi, bmiresult = '$bmiresult'
WHERE user_id=" . $_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
} else {
echo mysql_error();
}
}
This is my form which I am using bootstrap
<form method="post" action="<?php $_PHP_SELF ?>">
<h3> Height : <?php echo $userRow['height']; ?> cm</h3>
<input type="text" class="small" name="height" id="height" placeholder="Update Height CM"/>
<button type="submit" class="btn btn-warning" name="updateH"> UPDATE </button>
You appear to be trying to get everything about the user from the SESSION and I assume that information is not there. However, you read the users current data from the database, so all the existing values are available to you in $userRow so use those and your calculation will probably work.
Sidenote: Make sure the session has been started, and for all pages using sessions.
if(!isset($_SESSION['user']))
{
header("Location: PHOME.php");
exit; // stop further execution
}
$res=mysql_query("SELECT * FROM users WHERE user_id=".$_SESSION['user']);
if ( ! $res ) {
echo 'cannot find user ' . mysql_error();
}
$userRow=mysql_fetch_array($res);
if(isset($_POST['updateH']))
{
// if new data is supplied in $_POST use it,
// otherwise use the existing userRow values
$height = isset($_POST['height']) ? $_POST['height'] : $userRow['height'];
$weight = isset($_POST['weight']) ? $_POST['weight'] : $userRow['weight'];
$sex = $userRow['sex'];
$bmiresult = $userRow['bmiresult '];
//recalc BMI
$bmi = $weight/(($height/100)*($height/100));
if ($sex=="female")
{
if ($bmi <= 19)
$bmiresult="underweight!";
else if ($bmi>19 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
else if ($sex=="male")
{
if ($bmi <= 20)
$bmiresult="underweight!";
else if ($bmi>20 && $bmi<= 25)
$bmiresult="normal";
else if ($bmi > 25 && $bmi<= 30)
$bmiresult="overweight!";
else if ($bmi>30)
$bmiresult="OBESE!";
}
$sql = "UPDATE users ".
"SET height = $height ".
"SET bmi = $bmi".
"SET bmiresult = $bmiresult".
"WHERE user_id=".$_SESSION['user'];
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "<script type='text/javascript'>alert('Update Successfully!')</script>";
} else {
echo mysql_error();
}
}
As you are obviously just starting out on your PHP journey, please do not waste your time learning the mysql_ database extension as it is soon to be removed from PHP. Instead, spend your time learning either the mysqli_ or PDO extensions. See here for help deciding which Its quite a good read.
Your update statement should read:
$sql = "UPDATE users ".
"SET height = $height ".
" , bmi = $bmi".
" , bmiresult = $bmiresult".
"WHERE user_id=".$_SESSION['user'];
$result=mysql_query($sql);

if statement not working for MYSQL validation check

I am using the following code to determine if a user is signed in or not, I have set the field 'first_sign_in' to 0 in the mysql table but I am still receiving the echo 'already signed in for the start of the day when actually it should return 'not signed in for the start of the day'
Could someone help me on where I am going wrong here.
$time = date('h:i:s', time());
$checkifstaffexists = mysql_query("SELECT user_id from staff WHERE pin = 3012");
if (!$checkifstaffexists) {
die('Failed.');
}
if (mysql_num_rows($checkifstaffexists) > 0) {
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
if ($checkfirstsignin == 0) {
echo 'not signed in for start of day</br>';
$checksignintime = mysql_query("SELECT " . date("d") . " " . "_start from staff WHERE pin = 3012");
if($checksignintime > $time) {
echo 'user is late';
$addtolatetable = mysql_query("INSERT INTO lates (user_id, date_time) SELECT user_id, '2014-05-15 12:00:00' from staff WHERE pin = 3012");
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is not late';
//$signuserin = mysql_query(" ")
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
}
} else {
echo 'already signed in for start of day</br>';
$checkifuserisinourout = mysql_query("SELECT status from staff WHERE pin = 3012");
if ($checkifuserisinourout == 0) {
echo 'user is not signed in so we will sign you in';
//$signuserin = mysql_query(" ");
$changestatustoin = mysql_query("UPDATE staff SET status=1 WHERE pin = 3012");
//redirect
} else {
echo 'user is signed in so we will sign you out';
//$signuserout = mysql_query(" ");
$changestatustoout = mysql_query("UPDATE `staff` SET status=0 WHERE pin = '3012'");
//redirect
}
}
} else {
//The user cannot be found
echo 'User doesn\'t exist.';
}
with the line
$checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
you get back a resource that you have to use to fetch data, for example:
$row = mysql_fetch_assoc($checkfirstsignin);
and with this array ($row) you can work further.
Please check the manpage for mysql_query for further reading...
and since this will be posted all the time: mysql_* methods are deprecated, please use mysqli or pdo.
if ($checkfirstsignin == 0)
Will always equal true if the query succeeds even if there are no matching results.
You need to use mysql_fetch_row or mysql_fetch_array to do that.
while($row = mysql_fetch_assoc($checkfirstsignin)){
if($row['first_sign_in']==0){
//do something
}
}
Write this var_dump( $checkfirstsignin );
after this line $checkfirstsignin = mysql_query("SELECT first_sign_in from staff WHERE pin = 3012");
And you will see the returned result is an array, so it is always false on the next if check.

echoing two things in different if statements

if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$serv_id = $_POST['serv_id'];
$time = $_POST["time"];
$date = $_POST["date"];
if (!isset($_SESSION['id']))
{
echo "sorry you're not logged in.";
exit();
}
if(date('w', strtotime($date)) == 6 || date('w', strtotime($date)) == 0)
{
echo 'Event is on a weekend and cannot be booked.';
}
else
{
echo 'Thank for you booking with Claires hair and beauty';
$time = $time. ":00:00";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time' AND date = '$date'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
}
if(mysqli_num_rows($result) == 0)
{
$sql = "INSERT INTO tbl_booking (tbl_mem_id, serv_id, date, time) VALUES ('{$_SESSION['id']}','$serv_id','$date','$time')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
location: 'dashboard.php';
}
else
{
echo("this time is already booked");
}
}
Essentially I'm trying to make it check if they're logged in by checking a session variable, then check if the date they have entered is a weekend and then if the date/time being entered is already taken as if it is it just needs to echo this time is already booked.
But what is happening is when the slot is already taken? It echos
Thank for you booking with Claires hair and beautythis time is already booked
Try This Code:
if(date('w', strtotime($date)) == 6 || date('w', strtotime($date)) == 0)
{
echo 'Event is on a weekend and cannot be booked.';
}
else
{
$time = $time. ":00:00";
$result = mysqli_query($con, "SELECT time FROM tbl_booking WHERE time = '$time' AND date = '$date'") or trigger_error("Query Failed! SQL: $result - Error: ".mysqli_error($con), E_USER_ERROR);
}
if(mysqli_num_rows($result) == 0)
{
$sql = "INSERT INTO tbl_booking (tbl_mem_id, serv_id, date, time) VALUES ('{$_SESSION['id']}','$serv_id','$date','$time')";
mysqli_query($con, $sql) or die('Error: ' . mysqli_error($con));
echo 'Thank for you booking with Claires hair and beauty';//this is right place
location: 'dashboard.php';// Don't know what you trying to do here
}
else
{
echo("this time is already booked");
}
If you want to redirect to another page in php use this:
header('Location: yourpage.php');
PHP Header Function

Categories