当前位置: 动力学知识库 > 问答 > 编程问答 >

mysql - Setting the PHP SESSION user ID in my login function

问题描述:

Hi I was wondering if someone could please help me with my login function. Currently it will check to see if the username and password match an entry in the members table and if it does then sets the session variable authorised to true.

What Id like help with is when the session variable authorised has been set, I want to also set a user ID session variable, and by user ID I mean the numeric value - not the username which is in a column of the members table named memberID.

 <?php

function login($user, $pass){

//strip all tags from varible

$user = strip_tags(mysql_real_escape_string($user));

$pass = strip_tags(mysql_real_escape_string($pass));

$pass = md5($pass);

// check if the username and password combination exist in database

$sql = "SELECT * FROM members WHERE username = '$user' AND password = '$pass'";

$result = mysql_query($sql) or die('Query failed. ' . mysql_error());

if (mysql_num_rows($result) == 1) {

// the username and password match,

// set the session

$_SESSION['authorized'] = true;

// direct to admin

header('Location: '.DIRADMIN);

exit();

} else {

// define an error message

$_SESSION['error'] = 'Sorry, wrong username or password';

}

}

?>

Please note, I am aware that md5() isn't the best method for password encryption and mysql_real_escape_string() and mysql_num_rows() are deprecated as of PHP 5.5.

网友答案:

Supposing that the column name in your DB is userId, all you have to do is add

$_SESSION['userId'] = $result['userId']; 

under the line where you set the session.

So, it will look like

if (mysql_num_rows($result) == 1) {
      // the username and password match,
      // set the session
      $_SESSION['authorized'] = true;
      //set User Id
      $_SESSION['userId'] = $result['userId']; 

      // direct to admin
      header('Location: '.DIRADMIN);
      exit();
 }
分享给朋友:
您可能感兴趣的文章:
随机阅读: