PHP and SQL authentication uses 100% of database capacity - php

I've a webpage to a webinar with id 217, and to to verify if a user can watch the webinar, I use that function:
function user_verify($idlive, $register){
require("connect.php");
$query = "SELECT * FROM `users` WHERE idlive = 217 && register = '$register'";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
mysqli_close($conn);
if(isset($user)){
return 1;
} else {
return 0;
}
}
If return 1, I call the function to access the webinar:
function login($register){
require("connect.php");
$data_hora_inscricao = date('d/m/y H:i:s');
$query = "SELECT * FROM `users` WHERE register = '$register' && idlive = 217";
$result = mysqli_query($conn, $query);
$user = mysqli_fetch_assoc($result);
mysqli_close($conn);
if(isset($user)){
$data = [
'u_id' => $user['id'],
'u_name' => $user['nome'],
'u_email' => $user['email'],
'u_level' => $user['level'],
'u_time' => 0
];
$dadosUserCookie = serialize($data);
setcookie('d_user_217', $dadosUserCookie, time() + (86400 * 1), "/");
return 1;
} else {
return 0;
}
}
If it returns 1 (success), I set a cookie to request user data on other pages. It always worked well, until yesterday. I don't know what's going on, but my AWS Lightsail database shows me that this code is using 100% of database capacity. What I can do to solve this?

Related

Incorrect json output from mysql

I made a request from MySQL and my code below is not working:
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
if($rez){
$succes = 1;
} else {
$succes = 0;
}
$data = array("succes" => $succes);
echo json_encode($data);
In postman it shows me this:
You missed the data variable or your query doesn't not return any output. Please try to use the MySQL query in Phpmyadmin or CLI. If it is OK then use the code like :
$email =$_POST['email'];
$parola =$_POST['parola'];
$rez = mysqli_query($con, "SELECT * FROM utilizatori WHERE email='$email' AND parola='$parola'");
while($result = mysqli_fetch_array($rez))
{
$data[] = $result;
}
if(mysqli_num_rows($rez) != 0) {
$data = array("success" => "Success", "data" => $data );
} else {
$data = array("success" => "Failed", "data" => array() );
}
echo json_encode($data);

Fetch a specific row in mysql

I want to fetch a specific row from a table in my DB, i.e. only what's pertinent to the user that's logged in. I'm using the following script for this:
<?php
include('./classes/DB.php');
include('./classes/Login.php');
$connect = mysqli_connect("localhost", "root", "", "gaming");
$playerid = Login::isLoggedIn();
$sql = "SELECT * FROM games";// WHERE player_id =" .$playerid;
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
if ($row['player_id']==$playerid) {
$json_array[] = $row;
}
}
echo json_encode($json_array);
?>
Login.php:
<?php
class Login {
public static function isLoggedIn() {
if (isset($_COOKIE['CHEZA'])) {
if (DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])))) {
$userid = DB::query('SELECT user_id FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])))[0]['user_id'];
if (isset($_COOKIE['CHEZACHEZA'])) {
return $userid;
} else {
$cstrong = True;
$token = bin2hex(openssl_random_pseudo_bytes(64, $cstrong));
DB::query('INSERT INTO login_tokens VALUES (\'\', :token, :user_id)', array(':token'=>sha1($token), ':user_id'=>$userid));
DB::query('DELETE FROM login_tokens WHERE token=:token', array(':token'=>sha1($_COOKIE['CHEZA'])));
setcookie("CHEZA", $token, time() + 60 * 60 * 24 * 7, '/', NULL, NULL, TRUE);
setcookie("CHEZACHEZA", '1', time() + 60 * 60 * 24 * 3, '/', NULL, NULL, TRUE);
return $userid;
}
}
}
return false;
}
}
?>
I get the desired response in my browser but when I use a REST client all I get is an empty array [ ]. What am I doing wrong?
$playerid = Login::isLoggedIn();
is not set, check it.
EDIT
Now the code of isLoggedIn() is published: are you sure your REST client is sending the CHEZA cookie? I don't think it is a good idea to use cookies in REST call. I found useful this reading: https://softwareengineering.stackexchange.com/questions/141019/should-cookies-be-used-in-a-restful-api
Try modifying your php code to this, I have added an isset check before running your query and logic code :
<?php
include('./classes/DB.php');
include('./classes/Login.php');
$connect = mysqli_connect("localhost", "root", "", "gaming");
$playerid = Login::isLoggedIn();
if(isset($playerid)){
$sql = "SELECT * FROM games WHERE player_id =" .$playerid;
$result = mysqli_query($connect, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
if ($row['player_id']==$playerid) {
$json_array[] = $row;
}
}
echo json_encode($json_array);
}
?>
if it doesn't works, try adding a print_r($playerid) and check if you are getting the loggedin user id.

php file else condition output is wrong

Login.php
<?php
include 'Connection.php';
if(isset($_REQUEST["insert"]))
{
$user = $_GET['user'];
$pwd = $_GET['pass'];
//$sql =sqlsrv_query($conn,"select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'");
$sql = "select RegNo,UserName,password from Std_Reg where Username= '$user' and Password = '$pwd'";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (count($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["RegNo"] = $stmt["RegNo"];
$product["UserName"] = $stmt["UserName"];
$product["password"] = $stmt["password"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
array_push($result["product"], $product);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
?>
I have connected to MS SQL Server to PHP File.if condition work properly but else part is not work.I have wrong parameter passed its give output
{"success":1,"product":[{"RegNo":null,"UserName":null,"password":null}]}.
but right else part output is
{
"success": 0,
"message": "No product found"
}
After
$stmt = sqlsrv_query($conn, $sql);
$stmt is either FALSE (when there is a connectivity issue, a syntax error in the query or it refers an object that doesn't exist) or a PHP resource.
Because $stmt is neither an array nor an object that implements the Countable interface, count($stmt) always returns 1.
Use sqlsrv_num_rows() to get the number of rows returned by the query or (if you don't care about the number) use sqlsrv_has_rows():
$stmt = sqlsrv_query($conn, $sql);
if ($stmt) {
if (sqlsrv_has_rows($stmt) > 0) {
$row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array(
'RegNo' => $row['RegNo'],
'UserName' => $row['UserName'],
'password' => $row['password'],
);
$result = array(
'success' => 1,
'product' => array($product),
);
} else {
// no product found
$result = array(
'success' => 0,
'message' => 'No product found',
);
}
echo json_encode($result);
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);

retrieve session value and connect to different db in logout function

I am trying to set the company name in a session and retrieve the same to connect to a different database, i am setting the session using $this->session->set_userdata($newdata); and retrieving the session using $companyName = $this->session->userdata['newdata']['company']; but somehow retrieval is not happening and i am unable to load the correct db for updating logout information i.e it simply does not update the pr_system_attendance table by connecting to a different db. I am getting the correct value if i echo $company; after $company = $row1->company; this is FYI
My model code is as follows:
function check_admin_login(){
$this->db->where('username', trim($this->input->post('username')));
$this->db->where('userpass ', sha1(trim($this->input->post('userpass'))));
$this->db->where('status', '1');
$this->db->where('deleted', '0');
$this->db->select('*');
$query = $this->db->get($this->myTables['users']);
if($query->num_rows() > 0){
$row = $query->row();
$this->db->where('userid', $row->id);
$this->db->select('firstname,lastname,profileimage,company');
$query1 = $this->db->get($this->myTables['users_details']);
$row1 = $query1->row();
$newdata = array(
'is_admin_logged_in' => true,
'admin_user_name' => $row->username,
'admin_userpass' => $row->userpass,
'admin_id'=>$row->id,
'admin_lastlogin'=>date("d-m-Y H:i:s",$row->lastlogin),
'admin_lastloginip'=>$row->lastloginip,
'lastrefresh'=>time(),
'company'=>$row1->company
);
$company = $row1->company;
$this->session->set_userdata($newdata);
$companyName = $this->session->userdata['newdata']['company'];
$this->update_admin_login_time($this->session->userdata('admin_id'));
$this->admin_init_elements->set_global_user($row->username,$row->userpass);
if($this->input->post('remember'))
{
$cookie = array('name' => 'username','value' => $row->username,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie);
}
$name = $row1->firstname.' '.$row1->lastname;
$cookie1 = array('name' => 'name','value' => $name,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie1);
$cookie2 = array('name' => 'image','value' => $row1->profileimage,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie2);
return 'Login Successful';
}else{
return 'Incorrect Username or Password.';
}
}
function logout()
{
global $USER;
$companyName = $this->session->userdata['newdata']['company'];
$otherdb = $this->load->database("$companyName", TRUE);
$this->db->from("$companyName"."pr_users");
$query1 = $this->db->query("Select * from pr_system_attendance where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()");
date_default_timezone_set('Asia/Calcutta');
if($query1->num_rows() > 0)
{
$row = $query1->row();
$sql1 = "UPDATE pr_system_attendance set logout_time = '".date('Y-m-d H:i:s')."' where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()";
$query2 = $this->db->query($sql1);
}
$sql="UPDATE `".$this->myTables['users']."` SET
`if_online` = '0'
WHERE `id` = '".$USER->id."'" ;
$query=$this->db->query($sql);
}
Get session data with below line of code
//$companyName = $this->session->userdata['newdata']['company'];
$companyName = $this->session->userdata('company');

Unsuccessful Logins

So when the user unsuccessfully logs in for the first time it performs the tasks 70-73 and then it jumps down to 111. That part works correctly however when the chances left gets to 0 meaning the failedLogins value in the db would be 5 its supposed to do the steps starting at line 76 but it doesn't. Instead it shows 0 for the chances left and then that's it. I'm sure my logic is right but the the code is just placed in the wrong places.
Pastebin
// User is registered and verified
$query = "SELECT * FROM manager_users_logins_hacking WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
$row = mysqli_fetch_array($result);
$lockDate = $row['lockDate'];
// Find out if user is locked out of their account
if (($lockDate !== "0000-00-00 00:00:00") AND (strtotime($lockDate) <= time())) {
$currentDateTime = time();
$minutes = floor(($currentDateTime-$lockDate) / 60);
// Take minutes and perform tasks
if ($lockDate > 0 && $minutes < 10) {
// Calculate time remaining
$timeRemaining = 10 - $minutes;
// Account locked error
$output = array('errorsExist' => true, 'message' => 'Your account is currently locked, we appologize for the inconvienence. You must wait ' .$timeRemaining.' minutes before you can log in again!');
} else {
// Clear the lock
$query = "UPDATE manager_users_logins_hacking SET lockDate = NULL, hackerIPAddress = NULL, failedLogins = 0 WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
}
} else {
// Escape post data
$password = mysqli_real_escape_string($dbc,$_POST['password']);
// Assign hashed password to variable
$regenFromPostPW = reGenPassHash($password, $passwordDB2);
// Comparing the database password with the posted password
if ($passwordDB == $regenFromPostPW) {
$query2 = "UPDATE manager_users_logins SET numberOfLogins = numberOfLogins + 1, lastOnline = CURRENT_TIMESTAMP WHERE userID = '".$userID."'";
$result2 = mysqli_query($dbc,$query2);
// Assign user data into an array
$loggedinUserDataArray = array('userID' => $userID, 'name' => $firstName . " " . $lastName);
// Assign user data array to new session
$_SESSION['user_data'] = $loggedinUserDataArray;
// See if the remember me checkbox was checked
if (isset($_POST['remember'])) {
// Sets an expiration time for the cookie
$myExpiration = time()+60*60*24*100;
// Sets the cookie for the username
setcookie("username", $username, $myExiration, "/");
}
// Succesful login complete
$output = array('errorsExist' => false, 'message' => 'You have been logged in, please allow a moment while we load your account data!');
} else {
// Login unsuccessful
$query = "SELECT * FROM manager_users_logins_hacking WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
$row = mysqli_fetch_array($result);
$failedLogins = $row['failedLogins'];
// Take failed logins and compare it
if ($row['failedLogins'] >= 5) {
// Retrieve IP Address of user trying to hack into account
$hackerIPAddress = $_SERVER['REMOTE_ADDR'];
// Update database after account getting hacked and run query
$query = "UPDATE manager_users_logins_hacking SET lockDate = CURRENT_TIMESTAMP, hackerIPAddress = '".$hackerIPAddress."' WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
$query2 = "SELECT * FROM manager_users WHERE userID = '".$userID."'";
$result2 = mysqli_query($dbc,$query2);
$row = mysqli_fetch_array($result2);
$firstName = $row['firstName'];
$lastName = $row['lastName'];
// Email user new registration account
function my_domain_name() {
$my_domain = $_SERVER['HTTP_HOST'];
$my_domain = str_replace('www.', '', $my_domain);
return $my_domain;
}
$sender_email = "noreply#kansasoutlawwrestling.com";
$reply_to = "noreply#kansasoutlawwrestling.com";
$recipient_email = $email;
$email_subject = "KOW Manager Account Locked";
$email_body = 'Hello '.$firstName.' '.$lastName.' You, or someone using your account at '.my_domain_name().', has attempted to hack into your account. If this is an error, ignore this email and you will be removed from our mailing list.<br /><br />Regards, '.my_domain_name().' Team';
mailSomeone($email, $sender_email, $email_subject, $email_body);
// Account locked error
$output = array('errorsExist' => true, 'message' => 'Your account is currently locked, we appologize for the inconvienence. This is a security messure implimented by to many failed login\'s! You must wait 10 minutes before you can login again!');
} else {
$query = "UPDATE manager_users_logins_hacking SET failedLogins = '".$failedLogins."'+ 1 WHERE userID = '".$userID."'";
$result = mysqli_query($dbc,$query);
$query2 = "SELECT * FROM manager_users_logins_hacking WHERE userID = '".$userID."'";
$result2 = mysqli_query($dbc,$query2);
$row2 = mysqli_fetch_array($result2);
$failedLogins = $row2['failedLogins'];
// Calculate how many chances the user has to login before account gets locked
$chancesLeft = 5 - $failedLogins;
// Invalid username and password error
$output = array('errorsExist' => true, 'message' => 'Invalid Username and Password combination! You have ' .$chancesLeft.' chances left to login succesfully or the account will be locked!');
}
}
}
I try to debug your code and I suppose that code is right and does exactly what your describe. But it shows misleading message due to small bug: you execute update query and increment counter to one and after you select this value and use it in calculation. You should use old value in calculation, not a new one. Isn't it?
To fix this you may remove following useless lines:
$query2 = "SELECT * FROM manager_users_logins_hacking WHERE userID = '".$userID."'";
$result2 = mysqli_query($dbc,$query2);
$row2 = mysqli_fetch_array($result2);
$failedLogins = $row2['failedLogins'];
$lockDate is a datestring sometimes, and sometimes you try to subtract with it.
$currentDateTime = time();
$minutes = floor(($currentDateTime-$lockDate) / 60);
either this is a problem or strtotime($lockdate) above will be a problem.

Categories