Session in PHP Function - php

I'm new in php i create one function from where i'm login my session now i want to use this function for multiple time like for admin login too how i can use this function for multiple session. I updated my answer as per instruction of PacMan. Rightnow I'm doing it like this:
Code For USER & Admin Login:
//Check Wheather User Logged in or Not
if (isset($_SESSION['LoggedID']) && !empty($_SESSION['LoggedID'])){
$tableName = "prd_rgistration";
$id = $_SESSION['UserLogin'];
}else{
$tableName = "user_register";
$id = $_SESSION['AdminID'];
}
//Check Wheather User Logged in or Not
function Logged(){
if(LoggedIn()){
global $conn;
return $conn->query(sprintf('SELECT * FROM ' + $tableName + ' WHERE id = \'%d\'',$id))->fetchObject();
}else{
return (object)array();
}
}
function LoggedIn(){
return isset($id) && intval($id);
}
function redirect($Location){
header(sprintf('Location: %s',$Location),true,301);
exit;
}
if(LoggedIn()){
$User = Logged();
}
Admin Login Page Code
if($email_err == "" && $password_err == ""){
$Code = 0;
try{
$get_data = $conn->query("SELECT * FROM `user_register` WHERE `reg_email` = '$email' AND `reg_pass` = '$password' LIMIT 1");
if($get_data->rowCount() > 0){
$_SESSION['AdminID'] = $get_data->fetchObject()->id;
redirect('/domain.com/temp/admin/index.php');
}else{
$error = '<div class="alert alert-info">Invalid Email/Password</div>';
}
}catch(PDOException $E){
$Code = $E->getCode();
}
}
User Login Page Code
if($email_err == '' && $user_pass_err == ''){
$Code = 0;
try{
$get_data = $conn->query("SELECT * FROM `prd_rgistration` WHERE `email_db` = '$email' AND `password_db` = '$user_pass' LIMIT 1");
if($get_data->rowCount() > 0){
$_SESSION['UserLogin'] = $get_data->fetchObject()->id;
redirect('/domain.com/temp/index.php');
//redirect('/domain.com/index.php');
}else{
$error = '<div class="alert alert-info">Invalid Email/Password</div>';
}
}catch(PDOException $E){
$Code = $E->getCode();
}
}
Now It's giving Error Undefined AdminID and also not login user.

i can suggest you to follow this procedure it may be helpful , by changing the table name to a variable
if (isset($_SESSION['LoggedID']) && !empty($_SESSION['LoggedID'])){
$tableName = "prd_rgistration";
$id = $_SESSION['LoggedID'];
}else if(isset($_SESSION['adminID']) && !empty($_SESSION['adminID'])){
$tableName = "admin";
$id = $_SESSION['adminID']
}
//Check Wheather User Logged in or Not
function Logged(){
if(LoggedIn()){
global $conn;
return $conn->query(sprintf('SELECT * FROM '$tableName' WHERE id = \'%d\'',$id))->fetchObject();
}else{
return (object)array();
}
}
and here is it you have parametred only one function for both of usses admin and user login

Related

PHP/Session: Bring all data in table User after login

currently, I create a system that requires login. I Uses the LDAP method. I have created the session for this system. When I clicked the login button, it will go to the next page and display the "User_ID". Now, How I also want to display the user's full name on the next page after clicking the login button? The full name and the "User_ID" is on the same table 'staff'
Below is my current code.
<?php
include("config/configPDO.php");
session_start();
$msg = "";
if(isset($_POST['submitBtnLogin'])) {
$User_ID = trim($_POST['User_ID']);
$Pwd = trim($_POST['Pwd']);
if($User_ID != "" && $Pwd != "") {
$ldap_dn = "TOPNET\\".$User_ID;
$ldap_password = $Pwd;
$ldap_con = ldap_connect("ldap://172.xx.xx.xx:xxx");
ldap_set_option($ldap_con, LDAP_OPT_PROTOCOL_VERSION, 3);
if(#ldap_bind($ldap_con,$ldap_dn,$ldap_password)){;
try {
$records = $conn->prepare("SELECT Email, Role_ID FROM Staff WHERE User_ID = :User_ID ");
$records->execute(
array(
'User_ID' => $User_ID,
)
);
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if($results && count($results) > 0 ){
$_SESSION['login_user'] = $User_ID;
if($results["Role_ID"] == "2"){
header("location: pages/dashboard/dashboard_admin.php");
}else if ($results["Role_ID"] == "1"){
header("location: pages/dashboard/dashboard_super_admin.php");
}else if ($results["Role_ID"] == "3"){
header("location: pages/dashboard/dashboard_normal_user.php");
}
} else {
echo "
<script>alert('You're not authorized to use this system')</script>
<script>window.location = 'index.php'</script>
";
}
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
}
} else{
echo "
<script>alert('Invalid Email or Password')</script>
<script>window.location = 'index.php'</script>
";
}
} else {
$msg = "Both fields are required!";
}
}
?>
Why don't you save $results into $_SESSION['login_user'] and process it in the next page?

Cannot validate right? Why? New to PDO

I cant seem to validate right when i have an empty field or when the username is wrong or doesnt match. please any help or pointing me would be very helpful. I tried (empty but it doesnt seem to work when i fill in one field and the other is empty its says all fields are empty. and for the wrong credentials its not working at all.
INDEX.PHP
<?php
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
$log = $_SESSION['uid'];
if ($user->get_session($log)){
header("Location: profile.php?uid=".$log."");
}
if (isset($_REQUEST['submit'])) {
extract($_REQUEST);
$login = $user->check_login($emailusername, $password);
if(!empty($login)){
if($emailusername != $login){
if($password != $login){
if ($login) {
// Registration Success
$log_id = $_SESSION['uid'];
header("location: profile.php?uid=".$log_id."");
}
}else
echo "Incorrect Password";
}else
echo "Incorrect Email";
}else
echo "Fill in fields";
}
?>
USERS.PHP
<?php
include "db_config.php";
class User{
public $db;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
}
/*** for login process ***/
public function check_login($emailusername, $password){
$password = md5($password);
$sql2="SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
// this login var will use for the session thing
session_start();
$emaildb == $_SESSION['uemail'];
$_SESSION['login'] = true;
$_SESSION['uid'] = $user_data['uid'];
return true;
}
else{
return false;
}
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
Based on what you have, this is what you would need.
session_start();
include_once 'php/classes/class.user.php';
$user = new User();
// You need a conditional incase this session isn't set
$log = (isset($_SESSION['uid']))? $_SESSION['uid']:false;
if($log !== false && $user->get_session($log)){
header("Location: profile.php?uid=".$log."");
exit;
}
if(isset($_POST['submit'])) {
// This function should be validating your login so you don't need
// any comparisons after the fact.
$login = $user->check_login($_POST['email'], $_POST['password']);
if($login !== false)
header("location: profile.php?uid=".$log_id."");
exit;
else {
foreach($user->error as $kind => $err) {
echo '<h2>'.$kind.'</h2>'.'<p>'.$err.'</p>';
}
}
}
Your user class: You can throw error reporting into this class if you want to.
class User{
public $db;
public $error;
public function __construct(){
$this->db = new mysqli(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_DATABASE);
if(mysqli_connect_errno()) {
$this->error['db'] = "Error: Could not connect to database.";
echo $this->error['db'];
exit;
}
}
/*** for login process ***/
public function check_login($emailusername='', $password=''){
// Validate that your email is a real one
if(filter_var($emailusername,FILTER_VALIDATE_EMAIL) !== false) {
$password = md5($password);
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql2 = "SELECT uid from users WHERE uemail='$emailusername' or uname='$emailusername' and upass='$password'";
//checking if the username is available in the table
$result = mysqli_query($this->db,$sql2);
$user_data = mysqli_fetch_array($result);
$count_row = $result->num_rows;
if ($count_row == 1) {
$emaildb == $_SESSION['uemail'];
// this login var will use for the session thing
$_SESSION['username'] = $user_data['uemail'];
// $_SESSION['uemail'] = $user_data['uemail'];
$_SESSION['uid'] = $user_data['uid'];
$_SESSION['login'] = true;
}
else
$this->error['account'] = 'ERROR: Invalid Username/Password';
}
else
$this->error['email'] = 'ERROR: Invalid Email Address';
return (!isset($_SESSION['uemail']))? false:true;
}
/*** for showing the username or fullname ***/
public function get_fullname($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql = "SELECT * FROM users WHERE uid = $uid";
$result = mysqli_query($this->db, $sql);
$user_data = mysqli_fetch_array($result);
echo $user_data['fullname'], "<br/>";
echo $user_data['uemail'], "<br/>";
echo $user_data['uid'], "<br/>";
}
public function check_user($uid){
// --> You can prepare, bind, and execute your values here replacing what you have now....<--
$sql5 = "SELECT * from users WHERE uid='$uid'";
$result1 = mysqli_query($this->db, $sql5);
$count_row1 = $result1->num_rows;
return ($count_row1 == 1);
}
/*** starting the session ***/
public function get_session(){
return $_SESSION['login'];
}
public function user_logout() {
$_SESSION['login'] = FALSE;
session_destroy();
}
}
$login is a boolean variable, while $emailusername and $password are strings, why you compare them.

how to confirm logged in to pages?

I wonder how to make every pages that need go through login page. If the person doesn't log in, it will redirect to login page.
I include a function
confirm_logged_in();
in every page but it keeps asking for the login even after I log in. Please tell me how to fix that It only needs to log in once but still the keeps people from entering a direct link manually.
I do have session_start(); in every page!
Here the code for login page
$username = "";
if (isset($_POST['submit'])) {
$required_fields = array("username", "password");
validate_presences($required_fields);
if (empty($errors)) {// Attempt Login
$username = $_POST["username"];
$password = $_POST["password"];
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
} else{// Failure
$_SESSION["message"] = "Username/password not found.";
}
}
}
Here the code for functions:
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
function logged_in() {
return isset($_SESSION['admin_id'] );
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php");
}
}
function find_admin_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='admin' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$admin_set = mysqli_query($connection, $query);
confirm_query($admin_set);
if($admin = mysqli_fetch_assoc($admin_set)) {
return $admin;
} else {
return null;
}
}
function find_client_by_username($username) {
global $connection;
$safe_username = mysqli_real_escape_string($connection, $username);
$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE status='client' ";
$query .= "AND username = '{$safe_username}' ";
$query .= "LIMIT 1";
$client_set = mysqli_query($connection, $query);
confirm_query($client_set);
if($client = mysqli_fetch_assoc($client_set)) {
return $client;
} else {
return null;
}
}
function attempt_login_admin($username, $password) {
$admin = find_admin_by_username($username);
if ($admin) {
// found admin, now check password
if (password_check($password, $admin["hashed_password"])) {
// password matches
return $admin;
} else {
// password does not match
return false;
}
} else {
// admin not found
return false;
}
}
$found_admin = attempt_login_admin($username, $password);
$found_client = attempt_login_client($username, $password);
if ($found_admin) {
$_SESSION["admin_id"] = $found_admin["admin_id"];
$_SESSION["username"] = $found_admin["username"];
redirect_to("admin.php");
}elseif($found_client){
$_SESSION["client_id"] = $found_client["client_id"];
$_SESSION["username"] = $found_client["username"];
redirect_to("client.php");
}
I don't understand if the functions attempt_login_admin() and attempt_login_client() return a bool or an array. If you fix that, It should work. You can return a bool in the associative array by assigning the return bool value to $found_admin['bool'] and verifying the bool in the if-block by if($found_admin['bool']) { ... }.

PHP Login Script Broken

Hello Ladies and Gentlemen, I have been working on this project for some time now. And all of a sudden when I go into the web page to login I just get a blank screen at the 'success_login.php' which is literally just the login script that runs once login is clicked on my screen.
Here is the success_login.php script:
<?php
require_once($_SERVER['DOCUMENT_ROOT'] . '/luke/classes/userFunctions.php');
$userFunctions = new userFunctions();
session_start();
//assign all posted values to a session
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
$_SESSION['login_info'][$key] = $value;
}
}
//Get the username and password
$username = htmlentities($_POST["username"], ENT_QUOTES);
$password = htmlentities($_POST["password"], ENT_QUOTES);
//Get the user id if the login was valid
$userId = $userFunctions->validLogin($username,$password);
if($userId != 0) {
$_SESSION['login_info']['username'] = $username;
$_SESSION['login_info']['password'] = $password;
$_SESSION['login_info']['user_id'] = $userId;
header('LOCATION: home.php');
exit;
}
header('LOCATION: login.php');
exit;
?>
and here is the function it refers to:
public function validLogin($username,$password) {
$dbact = new DbInteraction();
$query = "select * from person";
$result = $dbact->interact($query,true);
$row = mysql_numrows($result);
$valid = false;
$userId = 0;
while ($row = mysql_fetch_array($result)) {
//Check to see if the username and password are valid
$validUsername = strcmp($username,$row['username']);
if($validUsername == 0) {
$hashedPassword = md5($password . Constants::SALTED);
$validPassword = strcmp($hashedPassword,$row['password']);
if($validPassword == 0) {
$valid = true;
$userId = $row['idperson'];
}
}
}
if(!$valid) {
$_SESSION['login_info']['username'] = "error";
$_SESSION['login_info']['password'] = "";
header('LOCATION: login.php');
exit;
return $userId;
} else {
$_SESSION['login_info']['username'] = "";
$_SESSION['login_info']['password'] = "";
return $userId;
}
}
Like I said, its been working for months and now all of a sudden its not anymore, and it has me really worried. Could someone shed some light for me?
Thanks a million for your time!

PHP 2 people logging in at the same time from the same computer pt.02

Does this look alright as a login script
//Player 1 Login username and password
$p1name = $_POST['p1name'];
$p1pass = $_POST['p1pass'];
//player 2 Login username and password
$p2name = $_POST['p2name'];
$p2pass = $_POST['p2pass'];
$connection = mysql_connect("db_host", "db_user", "db_pass");
mysql_select_db("db_name", $connection);
get_user($p1name, $p1pass);
get_user($p2name, $p2pass);
$row = $result;
$found = false;
if(($row["username"] == $p1name && $row["password"] == sha1("$p1pass"))
&& ($row["username"] == $p2name && $row["password"] == sha1("$p2pass")))
{
$found = true;
break;
}
function get_user($username, $password)
{
$query = 'SELECT * FROM users';
$query .= ' WHERE username = ' . mysql_real_escape_string($username);
$query .= ' AND password = ' . mysql_real_escape_string(sha1($password));
$result = mysql_query($query);
return mysql_fetch_assoc($result);
}
<?php
// Player 1 Login Information
$p1name = $_POST['p1name'];
$p1pass = $_POST['p1pass'];
// Player 1 Login Information
$p2name = $_POST['p2name'];
$p2pass = $_POST['p2pass'];
// Check user information
$player1 = get_user($p1name, $p1pass);
$player2 = get_user($p2name, $p2pass);
// Has any user been found?
$found = array(
'player1' => false,
'player2' => false
);
// Check if use information matches
if($player1['username'] == $p1name && $player1['password'] == $p1pass) {
$found['player1'] = true;
}
if($player2['username'] == $p2name && $player2['password'] == $p2pass) {
$found['player2'] = true;
}
function connect($db_host, $db_name, $db_pass, $db_table) {
$connection = mysql_connect($db_host, $db_name, $db_pass);
mysql_select_db($db_table, $connection);
}
function get_user($username, $password) {
$query = 'SELECT * FROM users';
$query .= ' WHERE username = ' . mysql_real_escape_string($username);
$query .= ' AND password = ' . mysql_real_escape_string(sha1($password));
$result = mysql_query($query);
return mysql_fetch_assoc($result);
}
You needed to create instances of the returned user information to check each players against their own.
Here is a tad bit cleaner idea. I suggest getting use to exceptions, they are great :)
function Login($uname, $passwd) {
$uname = mysql_real_escape_string($uname);
$passwd = mysql_real_escape_string($passwd);
// we are using sha encryption for user passwords
$passwd = sha1($passwd);
// lookup the user information they specified
$sql = mysql_query("SELECT * FROM `users` WHERE uname='$uname' && passwd='$passwd'");
try {
// if the username/password combo doesnt work/exist then tell them
if(!mysql_fetch_assoc($sql)) {
$error = new Error();
throw new Exception($error->Login(1));
// if the password DOES work, then continue the login
} else {
$_SESSION['login'] = 'true';
$_SESSION['uname'] = $uname;
redirect();
}
} catch (Exception $e) {
echo $e->GetMessage();
}
}
As far as the comments of "you cant store a session value for two users!!! ZOMG!" well.. if you MUST do this, simply store them in something like this.. $_SESSION['user1'] $_SESSION['user2']. This is simply an idea -- I'm not condoning this.

Categories