An user access to session of another user - php

Good evening, I tell you my problem. I have an application developed in PHP with Codeigniter running on a web hosting in Wiroos. Everything was working correctly, but as time passed, the application had more users who accessed simultaneously (obviously) and the following problem began to occur.
When user A logs in from location A, a session A is generated. If at the same time user B from location B accesses the application, user A's session is automatically loaded into its location B ... as it can Is this possible?
I show you the code of my application to see if you can help me
Login Controller
public function index($estadoLogin = 0){
if($this->session->userdata('estado_sesion'))
{
redirect(base_url()."panel");
}
$data['estadoLogin'] = $estadoLogin;
$data['title'] = "Iniciar Sesión - LandingApp";
$data['bodyClass'] = "external-page sb-l-c sb-r-c";
$this->load->view('templates/header',$data);
$this->load->view('login/loginbox', $data);
}//End method index
Login Method
public function ingresar(){
$correo = $this->security->xss_clean(strip_tags($this->input->post('correo')));
$pass = md5($this->security->xss_clean(strip_tags($this->input->post('password'))));
$Usuarios = new Usuario_Model();
$result = $Usuarios->login($correo, $pass);
if(count($result)>0){
foreach($result as $u){
$this->session->unset_userdata('id');
$this->session->unset_userdata('mail');
$this->session->unset_userdata('nombre');
$this->session->unset_userdata('activo');
$this->session->unset_userdata('logo_empresa');
$this->session->unset_userdata('nombre_empresa');
$this->session->unset_userdata('id_empresa');
$this->session->unset_userdata('nivel');
$this->session->unset_userdata('estado_sesion');
$this->session->set_userdata('id', $u->id);
$this->session->set_userdata('mail', $u->mail);
$this->session->set_userdata('nombre', $u->nombre);
$this->session->set_userdata('activo', $u->activo);
$this->session->set_userdata('nivel', $u->nivel);
$this->session->set_userdata('nombre_empresa', $u->nombre_empresa);
$this->session->set_userdata('id_empresa', $u->id_empresa);
$this->session->set_userdata('logo_empresa', $u->logo_empresa);
$this->session->set_userdata('avatar_user', $u->avatar_user);
$this->session->set_userdata('estado_sesion', TRUE);
redirect(base_url()."panel");
}//End foreach
}else{
$this->session->set_flashdata('mensaje', 'El usuario o password es incorrecto');
redirect(base_url()."login/index/1");
//$this->index(1);
}//End if
Panel Controller
public function index(){
$id = $this->session->userdata('id');
$id_empresa = $this->session->userdata('id_empresa');
$data_session['title'] = "Panel General";
$data_session['opcionMenu'] = "panel";
$data_session['bodyClass'] = "dashboard-page";
$data_session = $this->session_data_lib->set_data_session($data_session); //cargo las variables de sesion
if ($data_session['nivel']==1 || $data_session['nivel']==2){
$data_counters = $this->counters_lib->get_admin_counters(); //cargo las variables de contadores
}else{
$data_counters = $this->counters_lib->get_user_counters(); //cargo las variables de contadores
}
$this->load->view('templates/header', $data_session);
$this->load->view('templates/menu_top', $data_session);
$this->load->view('templates/menu_left', $data_counters);
if ($data_session['nivel']==0) {
$this->load->view('panel/panel_user',$data_counters);
}else{
$this->load->view('panel/panel_admin',$data_counters);
}
$this->load->view('templates/footer',$data_counters);
}//End method index
Session_Data_lib > set_data_session
public function set_data_session($data_session){
$data_lib_session['title'] = $data_session['title'];
$data_lib_session['opcionMenu'] = $data_session['opcionMenu'];
$data_lib_session['bodyClass'] = $data_session['bodyClass'];
$data_lib_session['nombre'] = $this->CI->session->userdata('nombre');
$data_lib_session['userid'] = $this->CI->session->userdata('id');
$data_lib_session['nivel'] = $this->CI->session->userdata('nivel');
$data_lib_session['avatar_user'] = $this->CI->session->userdata('avatar_user');
$data_lib_session['logo_empresa'] = $this->CI->session->userdata('logo_empresa');
$data_lib_session['nombre_empresa'] = $this->CI->session->userdata('nombre_empresa');
$data_lib_session['id_empresa'] = $this->CI->session->userdata('id_empresa');
$data_lib_session['arr_css'] = array("absolute_admin/assets/fonts/iconsweets/iconsweets.css");
$data_lib_session['lastSegs'] = $this->CI->panel_model->get10LastSeg($this->CI->session->userdata('id_empresa'));
return $data_lib_session;
}//End method set_data_session
I tried to migrate Codeigniter to version 3.0, and even make the following configuration in application / config / config.php
$config['sess_driver'] = 'database';
$config['sess_cookie_name'] = 'ci_sessions';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = 'ci_sessions';
$config['sess_match_ip'] = TRUE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
I do not know what else to try, I have the feeling that it can be a server configuration, but I still had no response from the support other than this:
Our servers have a micro-cache layer managed by nginx that may have
caused this behavior, now I deactivated it for your domain. Could you
please try it again?
Obviously the problem persists. I do not understand how it can be that two different users from different locations can access the session of the other at the time that both are consulting the server. I hope you can help me, thanks!

As I said in the comments you should update your passwords to use PHP's hash_password instead of md5
I can't say this is your issue, but you should verify that you do not have duplicate data in your users table. This code
public function ingresar(){
$correo = $this->security->xss_clean(strip_tags($this->input->post('correo')));
$pass = md5($this->security->xss_clean(strip_tags($this->input->post('password'))));
Specifically
$this->input->post('correo')
CI can return FALSE if the data is not set in the $_POST so if there is a problem you're are not checking if you are using FALSE for either one or both the password and the email. You should be checking like this, for example
public function ingresar(){
if(!$this->input->post('correo'))
//throw an error - stop execution, etc.
if(!$this->input->post('password'))
//throw an error - stop execution, etc.
/* ...continue on if both inputs are valid ... */
If you do not have unique fields set in your Database, you could have dozens of duplicate users with the same password and email. Both set to false
I can't tell this without knowing what constraints you have set on your DB fields for the user table. But, if you don't have the proper constraints then it may be possible to have multiple users with a password of false and an email of false ( at least according to your login code ) which would pass into your database lookup and pull multiple results.
The only way to know for sure is to look in PhpMyAdmin, at your user table, and see if you have duplicate passwords and emails in there.
Also in line with multiple users, you are not restricting login to 1 account only. Consider this part of your code.
public function ingresar(){
/* ..... */
if(count($result)>0){ //should expect only one user returned.
foreach($result as $u){
A loop here implies we are expecting one or more return records. This should throw an error if more then 1 user is returned. Emails should be unique and we should never have 2 or more users returned when looking up a user by his email. ( again without seeing the implementation of your User Model I can only guess ). But you should be explicitly checking like this:
public function ingresar(){
/* ..... */
if(count($result)==1){
//log user in
}else if(count($result)>1){
//this should never happen but it is, so you should pay attention here
}else{
//user not found or wrong password.
}
Something that could happen with the loop you have there, is that the session data will be overwritten until the last duplicate record. So everyone with a 'bad' account gets logged in as the last record pulled by the bad email data.
All in all I would say there are a lot of "holes" in your code that could allow this to happen under the right conditions. Most of this is "Guesses" based of what I can see an the loose constraints you have in place for login. The login is the gateway to your application and should be buttoned down much tighter then this.
PS. I used google translate, so I hope I read everything correctly.

Thanks for your replies. Problem was is micro-cache layer managed by NGINX. My hosting support disabled that and all works fine!

Related

Thread Modes Problems setting password for exiting user in Ion Auth

I have problems setting password for exiting user in Ion Auth, Version: 2.5.2, Codeigniter : 3.1.0-dev
In application/config/ion_auth.php I have by default :
$config['hash_method'] = 'bcrypt'; // sha1 or bcrypt, bcrypt is STRONGLY recommended
$config['default_rounds'] = 8; // This does not apply if random_rounds is set to true
$config['random_rounds'] = FALSE;
$config['min_rounds'] = 5;
$config['max_rounds'] = 9;
$config['salt_prefix'] = '$2y$';
$config['default_group'] = 'Members'; // Default group, use name
$config['admin_group'] = 'Admin'; // Default administrators group, use name
$config['identity'] = 'email'; // A database column which is used to login with
$config['min_password_length'] = 6; // Minimum Required Length of Password
$config['max_password_length'] = 20; // Maximum Allowed Length of Password
$config['email_activation'] = FALSE; // Email Activation for registration
$config['manual_activation'] = FALSE; // Manual Activation for registration
$config['remember_users'] = TRUE; // Allow users to be remembered and enable auto-login
//$config['user_expire'] = 986500; // How long to remember the user (seconds). Set to zero for no expiration
$config['user_expire'] = 0; // How long to remember the user (seconds). Set to zero for no expiration
$config['user_extend_on_login'] = TRUE; // Extend the users cookies every time they auto-login
$config['track_login_attempts'] = FALSE; // Track the number of failed login attempts for each user or ip.
$config['track_login_ip_address'] = TRUE; // Track login attempts by IP Address, if FALSE will track based on identity. (Default: TRUE)
$config['maximum_login_attempts'] = 3; // The maximum number of failed login attempts.
$config['lockout_time'] = 600; // The number of seconds to lockout an account due to exceeded attempts
$config['forgot_password_expiration'] = 0; // The number of milliseconds after which a forgot password request will expire. If
In my control I run :
$OkResult = $this->ion_auth_model->reset_password($lUserOperator['email'], $GeneratePassword) ;
AppUtils::deb($OkResult, '$OkResult::');
where $GeneratePassword is string like 'JKC3vmci', $lUserOperator['email'] is valid email of active user, value of returned value OkResult = 1
looking into db for updated user I see password value like '$2y$08$vyeSO30G4eQL3efuYbNii.VAlayDrAslKQNMDkdLYegggcsLWsQbe' and salt field is empty string(not NULL). But I can not login to system, but I login under usual login ok. What can be the reason of problem?
Also revieing code of ion_auth I see in reset_password function triggering events like post_change_password, post_change_password...
Could you please give ref to examples of using of this events?
In my control I run :
$OkResult = $this->ion_auth_model->reset_password(...
Why are you calling the ion_auth_model directly?
This is unnecessary and likely the cause of your troubles since you're bypassing much of Ion Auth's critical logic.
As per the developer's documentation:
NOTE: Methods available in the model are called through the controller using PHP5 magic. You should never use ion_auth_model->method() in your applications.
The developer has already provided many relevant functions you can use anywhere in your project. To update any user's account including resetting their password, you would use the update() class...
$id = 12; // <- Existing user's ID
$data = array(
'password' => '123456789', // <- NEW password
);
$this->ion_auth->update($id, $data); // <- Update the user's account
update() returns true if the update was successful and false if not.
If you don't know the user's id, then you simply do a standard database query on the "users" table to retrieve their id based on email address.
Could you please give ref to examples of using of this events?
See documenation: benedmunds.com/ion_auth

PHP SQL IF statement problems

Ok so I'm trying to pull some data from my SQL database and use it in an IF statement.
I have a database called DB_Default
and I have a table called Users
Inside Users I have all the normal columns such as id, username, password but I also have a column called isadmin.
I want to be able to do a mysql query through PHP selecting all users with the username $_SESSION[username] and isadmin = 1.
What I aim on doing is including a few navigation links for escalated privileged users only. So as the page that the code is going to be put into is for logged in users only I thought right, lets use the already defined username session i,e if my sessions username was set to Admin.
the statement should be
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
I have set $admin = "1"; so that it should only be able to return results if the user logged in has isadmin set to 1.
Instead I'm either having the navigation links show to any user regardless of their isadmin status or not at all.
To be honest the code is very messy as it's 5:40am and I haven't been coding for a while so quite rusty so I'm more than aware of how easy this should be of a fix.
I'm 99% sure it has to do with the fact I just set $admin = "1"; but for the life of me can't figure out where I've gone wrong. Going to give it a rest for today and come back tomorrow. Hopefully by then someone will have posted a resolution and obviously I'll vote up the best answer otherwise I'll give the code a lookover and see if I can't fix it myself!
Thanks!
UPDATE - Included code
<?php
$admin = 1;
$conn = mysql_connect("localhost","root","password");
mysql_select_db("DB_Default",$conn);
$result = mysql_query("SELECT * FROM users WHERE user_name='" . $_SESSION["user_name"] . "' and isadmin = '". $admin."'");
$row = mysql_fetch_array($result);
if(is_array($row)) {
$_SESSION["isadmin"] = $row[isadmin];
} else {
}
if($_SESSION["isadmin"] == '1'){
//has admin privs
} else {
//does not have admin privs
}
I have not yet set up the navigation links as I haven't gotten to that stage yet however the links would be inside the if statement admin links in the admin part and not in the non admin part.
My guess right now is going to be the following: You set the $_SESSION variable when you log in as Admin. After that the $_SESSION is never changed. Which pretty much means that if you log in as Admin and then re-log in as someone else, $_SESSION['isadmin'] will already be set to 1 thus providing full access. So what you will need to do is change the else part to:
if(is_array($row))
{ $_SESSION["isadmin"] = $row[isadmin]; }
else
{ $_SESSION['isadmin'] = 0; }

concrete5 programmatically created user can't log in

I've got a C5 site wherein I need to programmatically create user accounts. What I've done is use the register method of the UserInfo class, which seems to work. Problem is none of the users created this way are able to log in, the C5 login page just returns "Invalid email address or password."
I've checked and they are showing up in the users table. I've tried copying the password hash for a user who can log in, but the programmatically created user still can't log in. I've also asked another dev I know and after looking at the code says it's practically identical to how he's done this in the past. At this point I'm a bit stumped on how to move forward with troubleshooting this.
If it makes a difference the site is set to use email addresses instead of usernames for login.
//name = guy incognito \ both passed in
//email = 1234#5678.com \ via POST
function getRandomString($length) {
$seed = chr(mt_rand(97 ,122)).substr(md5(time( )), 1);
$rand = "";
for($y = 0; $y <= $length; $y++) {
$rand .= substr($seed, rand(0, strlen($seed)), 1);
}
return $rand;
}
$pswd = getRandomString(8);
$userData['uName'] = md5($name . rand(1, 1000) . date('Y-m-d H:i:s'));
$userData['uEmail'] = $email;
$userData['uPassword'] = $pswd;
$userData['uPasswordConfirm'] = $pswd;
$ui = UserInfo::register($userData);
Here's a screen capture of the entry created in the user table:
http://i.stack.imgur.com/N1ebw.png (unfortunately I lack the reputation to post images directly)
Edit - 19/09/2014
Having worked on this a little further I've traced the problem down into the checkPassword function of the 3rd party phpass library C5 is using. The hash it's generating when it checks during login is different than the hash generated at the time of account creation.
account creation hash = $2a$12$6UZ//BGdH6sO2AhfykvyHOLfzR2ADOuQVnzcFu6P9FckbJ56Y40WW
login attempt hash = $2a$12$6UZ//BGdH6sO2AhfykvyHOoxM727vGVnxo.3VsFYwDjKUM13SJqtO
After looking at concrete/core/dashboard/users/add.php I noticed they were registering users in a slightly different manner. Here they aren't passing a password confirmation, are specifying a default language, and most noticeably not calling UserInfo::Register but instead UserInfo::Add.
After updating my code to reflect how it was being done there things work. For the record:
$uName = md5($_POST['repName'] . rand(1, 1000) . date('Y-m-d H:i:s'));
$data = array('uName' => $uName, 'uPassword' => $authCode, 'uEmail' => $_POST['repEmail'], 'uDefaultLanguage' => 'En');
$ui = UserInfo::add($data);

Which way of a PHP login is the best way?

I'm coding a PHP script and I need a login. So I want to check the input against a database with username and password. Is the best way to do it by doing a query where I compare if the post data is the same (SQL function 'like') as in the database? After that I count the mysql rows. If it's zero, I deny the login. If it's one, I allow the login.
Is that the common and correct way of doing it or are there better ways? I want to have the best modern way. That's the reason why I'm using HTML5 too.
Some part of my code. Setting up cookies for the future cookie log-in and also setting attempts in the session to show the captcha if attempts exceeded certain number of logins.
(Hope you can understand it a bit)
Signin call
if($this->check_signin_errors()) {
if($this->signin($this->user_email, sha1($this->user_pass))) { //$user_pass hashed
header("Location: /account/");
exit();
} else {
$this->generate_captcha();
}
return true;
}
Signin function
private function signin($user_email, $user_pass) {
global $con;
$query = mysqli_query($con, "SELECT *, COUNT(id) FROM `accounts` WHERE `user_email` = '".mysqli_real_escape_string($con, $user_email)."' AND `user_pass` = '".mysqli_real_escape_string($con, $user_pass)."' AND access_level >= '0'");
$result = mysqli_fetch_assoc($query);
if($result['COUNT(id)'] > 0) {
$_SESSION['account_logged'] = true;
$_SESSION['user_id'] = $result['id'];
$_SESSION['user_email'] = $result['user_email'];
$_SESSION['user_pass'] = $result['user_pass'];
$_SESSION['access_key'] = $result['access_key'];
$_SESSION['access_level'] = $result['access_level'];
$this->set_cookie('cookie_name', '1/'.$_SESSION['user_email'].'/'.$_SESSION['user_pass'], 7776000);
$_SESSION['attempt'] = 1;
return true;
}
$_SESSION['account_logged'] = false;
$_SESSION['attempt'] = $_SESSION['attempt'] + 1;
$this->throw_error(5);
return false;
}
The most current approach would be to use the PHP 5.5 password hashing functions.
And because not everyone uses 5.5 yet, there is a library that implements it for earlier PHP versions.
Because hashing passwords uses a dynamic "salt", a random string, generated for each user individually, when logging in you actually need to read the user database to get the current hash, because when you want to compare the login password, you need the hash as second input to the password_verify() function.
So actually you try if you find the user in the database (do not use "LIKE" here, this is for searching with placeholders - your user should be able to type his username correctly). If none is found: no login. If two are found: You should add a unique index to the username, otherwise you'll have two users with the same name.
If one entry is found, you read it, compare the hashes, and then allow him further.

How to log user actions with php and mysql?

I'm working on my CMS and I want it to log activities by users and other admins.
For example: when new user registers or admin makes a new news post -> update last activity.
I want to know what is the best and easiest way.
Create a table in your database to
log your user activity.
Define the various activity types
that can happen in your App.
Create a common function that logs
any activity to that table.
Call that function from anywhere
you perform log-worthy activities in
your app.
You can then write a reporting tool that gives your admins access to those logged activities, you can filter by user, time and activity types.
In my log-framework, I specially mark activities which could be seen as malicious actions and assign them different numeric threat-values. If the sum of a user's thread-value reaches a certain threshold I log-out the user.
Ideally if you write an Application, you write your infrastructure code like logging at the very beginning and then use it in all your business logic code later.
Edit for cleanup:
Over time you may collect lots of records in that table. Depending on your requirements you could do different things.
Delete any entries older than x days (maybe a year)
Delete any entries of certain types older than x days, but keep entries of other types for longer, or forever.
Move entries older than a certain threshold into an archive log table. This keeps your main table small but allows you to access older log data if you really have to. I have a checkbox Use archive on my review logs page.
Basic Answer
Instead of doing this yourself, from scratch, check out how some existing systems do it, and if their license allows, use their design and code (make sure you document what code you've used and add a copyright notice to your CMS somewhere).
Possibly Helpful Example
I'm not sure about PHP CMS's which do this, but I know Django's admin app does. Django is implemented in Python, but it should be fairly straightforward to port this code over to PHP. Even if the code isn't a straight port, the design could be ported.
The file which contains the logging is in the admin module in models.py.
Some key aspects:
The data model for the logging table:
class LogEntry(models.Model):
action_time = models.DateTimeField(_('action time'), auto_now=True)
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType, blank=True, null=True)
object_id = models.TextField(_('object id'), blank=True, null=True)
object_repr = models.CharField(_('object repr'), max_length=200)
action_flag = models.PositiveSmallIntegerField(_('action flag'))
change_message = models.TextField(_('change message'), blank=True)
objects = LogEntryManager()
And the LogEntryManager, which saves the actual log entries:
class LogEntryManager(models.Manager):
def log_action(self, user_id, content_type_id, object_id, object_repr, action_flag, change_message=''):
e = self.model(None, None, user_id, content_type_id, smart_unicode(object_id), object_repr[:200], action_flag, change_message)
e.save()
I use two tables for activities, one that gives each activity an id, and another one that just logs the user id, activity id, and a timestamp. I do this because an int takes up less space than a string, so why log the same strings over and over? The second one isn't really necessary, you just just as easily keep the action codes in a text file for your own reference, but the db just seems like a easier place to remember.
In the past I've used a function to handle the actual logging actions, but the next time I do it I'm going to be using the Observer pattern. It appears to be a lot more flexible, and I've already had to edit out logging function calls from older code I have that wasn't going to log anything. I much prefer reusing code with no editing required.
Its very simple to do with PHP/JAVA FUNCTION JQUERY and its AJAX data posting method...
Before posting the solution -- Lets read these two lines
Why and What we want to record ?
--- As we know only to record transaction with in the database --not all the clicks and checks -- but yes its possible with this solution....
Here is the solution step by step: -
1. create a DB Table -- to record these things
a) Page Name.
b) logged in user name
c) session details (To record all the sessions).
d) POST/GET data details (To record all the post/get data for the
page)
e) Record Created Date.
or any other thing that you want to record.
2. Create a Jquery function or PHP function -- which will be auto triggered with every page.
3. This function will collect all the session of that page,user logged in details and what data passed to that page.
Apart from this - you can also record -- from which page this new page is called -- Its pretty simple and best way to implement loggs recording features even in already running old software's :)
If you want all the Code i mentioned above to use -- Search it over the NET the mechanism i have defined just you need FUNCTION CODE -- AUTO execute function code -- simple
PHP AND MYSQL
Create a Table to save the logs
CREATE TABLE `test_loq` (
id int(11) PRIMARY KEY AUTO_INCREMENT,
page varchar(255) NOT NULL,
username varchar(255) NOT NULL,
log_time datetime DEFAULT CURRENT_TIMESTAMP,
log_action longtext NOT NULL,
log_name varchar(255) NOT NULL,
user_id int(11) NOT NULL,
ip int(11) NOT NULL
)
explain :
log_action is the kind of action made here you can write a lot of information about the action that has been made.
page is the page that the action was made of, the name of the php file
log_name is the name of the action that was done
username is the name of the user that hade made this action
user_id is the id of the user that made this action
ip is the ip adress of the user
2. Create a Class
class log
{
CONST ENVIRONMENT = 'developemnt';
private $id;
protected $log_action;
protected $username;
protected $page;
protected $ip;
protected $log_name;
private $user_id;
public function __construct(string $log_action, string $username, string $log_name)
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
if(!empty($_SESSION['id'])){
$id = $_SESSION['id'];
} else {
$id = 0;
}
$this->log_action = $log_action;
$this->username = $username;
$this->log_name = $log_name;
$this->user_id = $id;
$this->page = basename($_SERVER['PHP_SELF']);
$this->ip = $ip;
}
public function createAction()
{
global $conn;
if(!$conn) {
echo mysqli_error($conn); die;
}
$sql = "INSERT INTO test_log (`log_action`,`username`,`log_name`,`page`,`user_id`,`ip`) values ('".$this->log_action."','".$this->username."','".$this->log_name."','".$this->page."','".$this->user_id."','".$this->ip."')" ;
$sql_query = mysqli_query($conn,$sql);
if(!$sql_query){
echo mysqli_error($conn); die;
}
if(ENVIRONMENT == 'development'){
$_SESSION['msg'] = 'A new log was created ' . $this->log_name;
}
} }
explain:
ENVIRONMENT can be development or production , if it's in development it will show flash messages about the log that has been made
3.Log An Action!
example: log action for login attempts
Create a php file logincheck.php
<?php
session_start();
include("include/configurationadmin.php");
//include_once('../include/classes/config.inc.php');
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$sql = mysqli_query($conn,"select * from ".$sufix."admin where username='".$username."'") ;
// HERE HOW TO LOG ACTION
$log = new log("Logging in attempt from $username" , $username ,'Login Attempt' );
$log->createAction();
//SIMPLE AND COOL RIGHT?
if(mysqli_num_rows($sql) > 0)
{
$rows = mysqli_fetch_assoc($sql);
if(md5($password) == $rows['password']) {
$_SESSION['id'] = $rows['id'];
$_SESSION['username'] = $rows['username'];
$_SESSION['usertype'] = $rows['type'];
mysqli_query($conn,"update ".$sufix."admin set lastlogin='".date('Y-m-d')."' where id = '".$rows['id']."' and username='".$rows['username']."'") ;
$domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false;
setcookie('rrdssrdda', $rows['id'], time()+120, '/', $domain, false);
header("Location: http://localhost/test/admin-new/dashboard");
exit();
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
}
} else {
$_SESSION['message']="<div class='alert alert-danger' role='alert'>Invalid userid/password!</div>";
header("Location: http://localhost/test/admin-new/");
exit();
} ?>
Happy Coding!

Categories