1

我正在尝试从登录脚本传递一个会话变量以显示一个欢迎 [用户名] 按摩,目前它没有通过它 - 有什么想法吗?我对 PHP 很陌生,因此非常感谢您的所有评论。

代码如下。

<?php
ob_start(); // Start output buffering

session_start(); //must call session_start before using any $_SESSION variables
$_SESSION['username'] = $username;

function validateUser()
{

    session_regenerate_id (); //this is a security measure
    $_SESSION['valid'] = 1;
    $_SESSION['username'] = $username;
}

      $username = isset($_POST['username'])?$_POST['username']:'';
     $password = isset($_POST['password'])?$_POST['password']:'';

//connect to the database here

$hostname_PropSuite = "localhost";
$database_PropSuite = "propsuite";
$username_PropSuite = "root";
$password_PropSuite = "root";
$PropSuite = mysql_pconnect($hostname_PropSuite, $username_PropSuite, $password_PropSuite) or trigger_error(mysql_error(),E_USER_ERROR); 
mysql_select_db($database_PropSuite, $PropSuite);

$username = mysql_real_escape_string($username);

$query = "SELECT password, salt FROM admin_users WHERE username = '$username';";

$result = mysql_query($query) or die(mysql_error());

if(mysql_num_rows($result) < 1) //no such user exists
{
    header('Location: http://localhost/PropSuite/index.php?login=fail');

    die();
}
$userData = mysql_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );
if($hash != $userData['password']) //incorrect password
{
    header('Location: http://localhost/PropSuite/index.php?login=fail');

    die();
}
else
{
   validateUser(); //sets the session data for this user
}
//redirect to another page or display "login success" message
header('Location: http://localhost/PropSuite/main');
die();




//redirect to another page or display "login success" message


?>
4

3 回答 3

3

我认为您的问题是您$_SESSION['username'] = $username;在定义 $username 之前使用。$username = isset($_POST['username'])?$_POST['username']:'';需要在上面$_SESSION['username'] = $username;

于 2012-10-25T16:59:01.270 回答
3

在函数中添加用户名作为参数

function validateUser($username)
{
    session_regenerate_id (); //this is a security measure
    $_SESSION['valid'] = 1;
    $_SESSION['username'] = $username;
}

当你调用它时传递它

validateUser($username); //sets the session data for this user
于 2012-10-25T16:59:30.150 回答
1

要从函数中访问在全局范围内声明的变量,您必须使用global关键字,如下所示:

function validateUser()
{
    global $username;//NEEDED to access $username declared in global scope
    session_regenerate_id (); //this is a security measure
    $_SESSION['valid'] = 1;
    $_SESSION['username'] = $username;
}
于 2012-10-25T16:59:33.897 回答