I posted this same question on StackOverflow but guys over there told me to post it here.
I have programming in PHP since past 2 years and yet haven't found a perfect script for logging the user in. It's very messy when it comes to deciding whether to use Session or Cookies or both. What value to assign to the Session ID? Whether to store that value in MySQL table or not. How to auto-login the user? And so on...
I've been using this code for few months. Please tell me whether this is fine.
This is the main signin
function.
<?php
//this function is called after sanitizing the user-input
//$u is username and $p is password
function signin($u,$p) {
global $conn, $current_user, $signin_stat, $incorrect;
$q_string="SELECT uid FROM users WHERE (emailid='$u' OR uname='$u') AND AES_DECRYPT(pass,CONCAT(uname,'$p'))='$p'";
$q=$conn->query($q_string);
if($q->num_rows==1) {
$c=$q->fetch_row();
$uid=$c[0]; //getting uid
$current_user=new User($uid); //creating $current_user object
set_session($uid); //setting session
$signin_stat=1;
return true;
} else {
signout(0);
$incorrect=1;
return false;
}
}
?>
This is the set_session()
function :
<?php
function set_session($uid) {
global $conn;
$sid=sha1($uid+time()+$_SERVER['REMOTE_ADDR']);
$q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
$q=$conn->query($q_string);
$_SESSION['user_session']=$sid;
if($q) return true; else return false;
}
?>
This is the auto_signin
script :
<?php
if(isset($_SESSION['user_session'])) {
$sid=$_SESSION['user_session'];
global $conn, $current_user;
$q_string="SELECT uid FROM users WHERE sid='$sid'";
$q=$conn->query($q_string);
if($q->num_rows==1) {
$c=$q->fetch_row();
$uid=$c[0];
$current_user=new User($uid);
$signin_stat=1;
$current_user->update_online_stat();
} else {
signout(0);
}
}
?>
This is the signout()
function
<?php
function signout($uid) {
global $conn, $current_user, $signin_stat;
$sid='NULL';
$q_string="UPDATE users SET sid='$sid' WHERE uid=$uid";
$q=$conn->query($q_string);
$signin_stat=0;
$current_user=0;
$_SESSION['user_session']='';
unset($_SESSION['user_session']);
unset($_POST);
session_destroy();
}
?>
notes :
$conn
is the mysqli object
$current_user
is the user object
sid
is the field in mysql users table which holds the current session id of the respective user.
Is this script fine or would you suggest some changes?
Or is this completely crap and needs to be written again from scratch?
Please help me out.
$conn
variable which is the MySQLi object. Should I declare it again and again in every function? And other objects which are frequently accessed shouldn't also be declared global? \$\endgroup\$