【问题标题】:How to let the user only edit their details and no one elses如何让用户只编辑他们的详细信息而没有其他人
【发布时间】:2022-01-12 03:25:36
【问题描述】:

我最近创建了一个非常基本的网站,用户可以在其中登录,然后可以访问他们可以编辑的表格。我希望用户只能编辑自己的详细信息,而不能编辑其他人,而且我不知道应该在代码中添加什么才能做到这一点。 Here is what the edit page looks like atm(我知道这样显示密码不是很安全,这只是一个例子)

更新: 我不知道我应该向删除页面添加什么值,因此它只会删除登录用户的详细信息,而不会删除其他任何人的详细信息。目前它不会删除任何细节。 这是我的注册页面

<?php
// Include config file
require_once "pconfig.php";
 
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Validate username
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter a username.";
    } elseif(!preg_match('/^[a-zA-Z0-9_]+$/', trim($_POST["username"]))){
        $username_err = "Username can only contain letters, numbers, and underscores.";
    } else{
        // Prepare a select statement
        $sql = "SELECT id FROM users WHERE username = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            
            // Set parameters
            $param_username = trim($_POST["username"]);
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                /* store result */
                mysqli_stmt_store_result($stmt);
                
                if(mysqli_stmt_num_rows($stmt) == 1){
                    $username_err = "This username is already taken.";
                } else{
                    $username = trim($_POST["username"]);
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Validate password
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter a password.";     
    } elseif(strlen(trim($_POST["password"])) < 6){
        $password_err = "Password must have atleast 6 characters.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate confirm password
    if(empty(trim($_POST["confirm_password"]))){
        $confirm_password_err = "Please confirm password.";     
    } else{
        $confirm_password = trim($_POST["confirm_password"]);
        if(empty($password_err) && ($password != $confirm_password)){
            $confirm_password_err = "Password did not match.";
        }
    }
    
    // Check input errors before inserting in database
    if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
        
        // Prepare an insert statement
        $sql = "INSERT INTO users (username, password) VALUES (?, ?)";
         
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
            
            // Set parameters
            $param_username = $username;
            $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Redirect to login page
                header("location: plogin.php");
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sign Up</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 360px; padding: 20px; }
    </style>
</head>
<body>
    <div class="wrapper">
        <h2>Sign Up</h2>
        <p>Please fill this form to create an account.</p>
        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>    
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $password; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group">
                <label>Confirm Password</label>
                <input type="password" name="confirm_password" class="form-control <?php echo (!empty($confirm_password_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $confirm_password; ?>">
                <span class="invalid-feedback"><?php echo $confirm_password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Submit">
                <input type="reset" class="btn btn-secondary ml-2" value="Reset">
            </div>
            <p>Already have an account? <a href="plogin.php">Login here</a>.</p>
        </form>
    </div>    

这是我的登录页面

<?php
// Initialize the session
session_start();
 
// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: allcontacts.php");
    exit;
}
 
// Include config file
require_once "pconfig.php";
 
// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = $login_err = "";
 
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
 
    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }
    
    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }
    
    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password FROM users WHERE username = ?";
        
        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);
            
            // Set parameters
            $param_username = $username;
            
            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);
                
                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();
                            
                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;                            
                            
                            // Redirect user to welcome page
                            header("location: allcontacts.php");
                        } else{
                            // Password is not valid, display a generic error message
                            $login_err = "Invalid username or password.";
                        }
                    }
                } else{
                    // Username doesn't exist, display a generic error message
                    $login_err = "Invalid username or password.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }
    
    // Close connection
    mysqli_close($link);
}
?>
 
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 360px; padding: 20px; }
    </style>
</head>
<body>
    <div class="wrapper">
        <h2>Login</h2>
        <p>Please fill in your credentials to login.</p>

        <?php 
        if(!empty($login_err)){
            echo '<div class="alert alert-danger">' . $login_err . '</div>';
        }        
        ?>

        <form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
            <div class="form-group">
                <label>Username</label>
                <input type="text" name="username" class="form-control <?php echo (!empty($username_err)) ? 'is-invalid' : ''; ?>" value="<?php echo $username; ?>">
                <span class="invalid-feedback"><?php echo $username_err; ?></span>
            </div>    
            <div class="form-group">
                <label>Password</label>
                <input type="password" name="password" class="form-control <?php echo (!empty($password_err)) ? 'is-invalid' : ''; ?>">
                <span class="invalid-feedback"><?php echo $password_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Login">
            </div>
            <p>Don't have an account? <a href="pregister.php">Sign up now</a>.</p>
        </form>
    </div>
</body>
</html>

这是我的联系页面

<!DOCTYPE html>
<html>
    <head>
    <meta charset="utf-8">
        <title>Display Contacts</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        body{ font: 14px sans-serif; }
        .wrapper{ width: 360px; padding: 20px; }
    </style>
    </head>
<body>
    
<!DOCTYPE html>
<html>
<head>
  <title>Display all records from Database</title>
</head>
<body>

<h2>Users</h2>

<table border="2">
  <tr>
    <td>Sr.No.</td>
    <td>Full Name</td>
    <td>Password</td>
    <td>Edit</td>
    <td>Delete</td>
  </tr>

<?php

include "pconfig.php"; // Using database connection file here

$records = mysqli_query($link,"select * from users"); // fetch data from database

while($data = mysqli_fetch_array($records))
{
?>
  <tr>
    <td><?php echo $data['id']; ?></td>
    <td><?php echo $data['username']; ?></td>
    <td><?php echo $data['password']; ?></td>    
    <td><a href="edit.php?id=<?php echo $data['id']; ?>">Edit</a></td>
    <td><a href="delete.php?id=<?php echo $data['id']; ?>">Delete</a></td>
  </tr> 
<?php
}
?>
</table>

</body>
</html>

最后是我的删除页面

<?php

include "pconfig.php"; // Using database connection file here



$id = $_GET['id']; // get id through query string
if($param_username == "$id") {
   $del = mysqli_query($link,"delete from users where id = '$id'"); // delete query
mysqli_close($link); // Close connection
    header("location:allcontacts.php"); // redirects to all records page
    exit;
}
else
{
 echo "Error deleting record"; // display error message if not delete
}

?>

【问题讨论】:

  • 不允许用户访问数据库。而是为用户请求数据,然后在清理后为用户保存数据。
  • 请贴出您的登录相关代码(登录表单及相关php/mysql代码)
  • @KenLee 刚刚做了

标签: php sql database


【解决方案1】:

开始的一种方法是,在为该表生成每个 (HTML) 行时,不要回显/输出“编辑”/“删除”链接,除非当前用户的 UserId 等于该行的 UserId。此外,单击“编辑”/“删除”链接时发生的任何情况都应仅在记录的 UserId 与当前用户的 UserId 相同时运行。

另一个想法,当最初加载(HTML)表以查看记录时,只在数据库中查询与当前用户相关的行。这样您就无需在添加“编辑”/“删除”链接之前进行任何进一步检查。

更新: 一些额外的想法。

不要将您的数据库列命名为“id”。这太模棱两可了。它需要更加明确,这样当您连接多个表并引用它们的“id”列时,您就不会同时处理对不同“id”的多个引用。

在“联系人”页面的顶部也包含此代码。

// Initialize the session
session_start();

// Check if the user is already logged in
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true)
{
    $userId = $_SESSION['id'];
}
else
{
    $userId = null;
}

然后,对于联系人表的最后两个单元格,重写它们以在回显编辑或删除链接之前检查用户的 ID。

<!-- BEFORE -->
<td><a href="edit.php?id=<?php echo $data['id']; ?>">Edit</a></td>
<td><a href="delete.php?id=<?php echo $data['id']; ?>">Delete</a></td>

<!-- AFTER -->
<?php if($userId && $userId == $data['id]) { ?>
    <td>
        <a href="edit.php?id=<?=$data['id'];?>">Edit</a>
    </td>
    <td>
        <a href="delete.php?id=<?=$data['id'];?>">Delete</a>
    </td>

<?php } else { ?>
    <td></td>
    <td></td>
<?php } ?>

这将只允许用户编辑/删除他/她自己的联系人记录。

但是!您真的需要在“edit.php”和“delete.php”脚本文件中验证这些操作!如果黑客知道他/她可以通过调用 php 脚本文件并在 GET 请求中提供一个“id”参数来删除联系人,那么他/她就可以很容易地使用您的数据进行 F 操作。

祝你好运!

【讨论】:

  • 我更新了我的问题
【解决方案2】:

您必须创建一个包含用户详细信息的表,例如“用户”。现在,当您的用户成功登录时,您必须根据安全存储用户 ID 的应用程序生成 cookie 或会话。然后当用户想要更改详细信息时,请检查 ID 是否匹配。此外,在字体端只显示登录的用户信息。

登录(表格)

  • ID
  • 电子邮件
  • 密码

用户(表)

  • ID
  • 姓名
  • 地址

【讨论】:

    猜你喜欢
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多