php - 使用用户 ID 登录后重定向

标签 php mysql authentication

我正在尝试使这个脚本按如下方式工作......

用户登录后,他们会转到以下链接 index.php?id=1 (userid)

但是我试过很多方法这里是下面的代码

<?php 
// Include required MySQL configuration file and functions 
require_once('config.inc.php'); 
require_once('functions.inc.php'); 

// Start session 
session_start(); 
  $_SESSION['user_id']= $id;
// Check if user is already logged in 
if ($_SESSION['logged_in'] == true) { 

              // If user is already logged in, redirect to main page 
              redirect('../index.php'); 
} else { 
              // Make sure that user submitted a username/password and username only consists of alphanumeric chars 
              if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR 
                   (!ctype_alnum($_POST['username'])) ) { 
                            redirect('../login.php'); 
              } 

              // Connect to database 
              $mysqli = @new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE); 

              // Check connection 
              if (mysqli_connect_errno()) { 
                            printf("Unable to connect to database: %s", mysqli_connect_error()); 
                            exit(); 
              } 

              // Escape any unsafe characters before querying database 
              $username = $mysqli->real_escape_string($_POST['username']); 
              $password = $mysqli->real_escape_string($_POST['password']);

              // Construct SQL statement for query & execute 
              $sql              = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'"; 
              $result = $mysqli->query($sql); 

              // If one row is returned, username and password are valid 
              if (is_object($result) && $result->num_rows == 1) { 
                            // Set session variable for login status to true 
                            $_SESSION['logged_in'] = true; 
                            redirect('../index.php?id=' . $_SESSION['user_id']);
              } else { 
                            // If number of rows returned is not one, redirect back to login screen 
                            redirect('../login.php'); 
              } 
} 
?> 

这不是一个实时项目,也永远不会只是为了我的学习曲线。

当前代码转到以下链接 index.php?id=


CD001 回答后更新代码

<?php 
// Include required MySQL configuration file and functions 
require_once('config.inc.php'); 
require_once('functions.inc.php'); 

// Start session 
session_start(); 

// Check if user is already logged in 
if ($_SESSION['logged_in'] == true) { 
              // If user is already logged in, redirect to main page 
              redirect('../index.php'); 
} else { 
              // Make sure that user submitted a username/password and username only consists of alphanumeric chars 
              if ( (!isset($_POST['username'])) || (!isset($_POST['password'])) OR 
                   (!ctype_alnum($_POST['username'])) ) { 
                            redirect('../login.php'); 
              } 

              // Connect to database 
              $mysqli = @new mysqli(DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE); 

              // Check connection 
              if (mysqli_connect_errno()) { 
                            printf("Unable to connect to database: %s", mysqli_connect_error()); 
                            exit(); 
              } 

              // Escape any unsafe characters before querying database 
              $username = $mysqli->real_escape_string($_POST['username']); 
              $password = $mysqli->real_escape_string($_POST['password']); 

              // Construct SQL statement for query & execute 
              $sql              = "SELECT * FROM users WHERE username = '" . $username . "' AND password = '" . md5($password) . "'"; 
              $result = $mysqli->query($sql); 

              // If one row is returned, username and password are valid 
             if (is_object($result) && $result->num_rows == 1) { 
    $iUserId = null;
    $oUser = $result->fetch_object();

    //there's only 1 record but what the hey
    while($oUser = $result->fetch_object()) {
      $iUserId = (int) $oUser->id; // assuming the field in the user table is called `id`
    }

    // Set session variable for login status to true 
    if(!is_null($iUserId)) {
      $_SESSION['logged_in'] = true; 
      redirect('../index.php?id=' . $iUserId);
    }

    //error trapping


              } else { 
                            // If number of rows returned is not one, redirect back to login screen 
                            redirect('../login.php'); 
              } 
} 
?> 

当我尝试登录时出现错误

\includes\login.inc.php 第 10 行

第10行是这个

if ($_SESSION['logged_in'] == true) { 

最佳答案

你有:

// If one row is returned, username and password are valid 
if (is_object($result) && $result->num_rows == 1) { 
            // Set session variable for login status to true 
            $_SESSION['logged_in'] = true; 
            redirect('../index.php?id=' . $_SESSION['user_id']);
}

但是在您定义的文档的顶部:

$_SESSION['user_id']= $id;

但是,$id 在那个时间点实际上并没有定义,除非它包含在文档顶部的一个必需文件中(我认为这不太可能)。

您应该从数据库结果对象 ($result) 中检索用户 ID。

类似于:

// If one row is returned, username and password are valid
if (is_object($result) && $result->num_rows == 1) { 
    $iUserId = null;
    $oUser = $result->fetch_object();

    //there's only 1 record but what the hey
    while($oUser = $result->fetch_object()) {
      $iUserId = (int) $oUser->id; // assuming the field in the user table is called `id`
    }

    // Set session variable for login status to true 
    if(!is_null($iUserId)) {
      $_SESSION['logged_in'] = true; 
      redirect('../index.php?id=' . $iUserId);
    }

    //error trapping
    else {
      //throw an Exception or something to trap the invalid user id
    }
}

对于 mysqli_result 对象,请参见: http://www.php.net/manual/en/class.mysqli-result.php

尤其是方法: http://www.php.net/manual/en/mysqli-result.fetch-assoc.php http://www.php.net/manual/en/mysqli-result.fetch-object.php

mysqli_result 对象基本上包含整个结果集,您需要遍历它以获取单独的记录 - 尽管您只有 1 条记录可以使用:

$result->data_seek(0);
$oUser = $result->fetch_object();
$iUserId = (int) $oUser->id; //assuming the user id field is called 'id'

顺便说一句:可以说,更好的做法是让 SQL 查询匹配用户名并检索 ID 和密码 - 然后在应用程序而不是数据库中评估密码;它进一步降低了注入(inject)攻击起作用的机会,意味着您可以使用应用程序中的散列和加盐对象更好地加密您的密码。

关于php - 使用用户 ID 登录后重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21336153/

相关文章:

php - 奇怪的 PDO 行为

php - 单个 mysqli 查询语句获取总行数和限制

php - 如何在wordpress中并排放置两个div

PHP 64位整数哈希

php - Laravel 属于合并?

ruby-on-rails - Devise + Omniauth-Facebook 获取用户的电话#

php - 是否可以将触发器错误消息显示到网页?

mysql - 我可以保留对连接表中的元素的订单吗?

php - cakePHP isAuthorized 不工作

php - 浏览器选项卡关闭时销毁 session