如何让用户只删除他们的详细信息而没有其他人的php

Posted

技术标签:

【中文标题】如何让用户只删除他们的详细信息而没有其他人的php【英文标题】:How to let user only delete their details and no one elses php 【发布时间】:2022-01-13 10:03:59 【问题描述】:

我创建了一个非常基本的网站,用户可以在其中登录,然后可以访问他们可以编辑的表格。我希望用户只能删除他们自己的详细信息而不能删除其他人,而且我不知道我应该在删除页面中添加什么,所以它只会删除登录用户的详细信息而不删除别人的。目前它不会删除任何细节。

这是我的注册页面

<?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


?>

【问题讨论】:

请仅提供必要的最少代码来澄清您的问题。没有人会读到这一切…… 是的,代码有点太多了。但它让我看到您将用户 ID 存储在会话中。您应该使用它来删除属于该用户的数据,而不是作为 URL 参数给出的用户 ID。 // Password is correct, so start a new session session_start(); 实际上会在日志中生成警告,说明会话已经开始,然后重新使用会话。但我不认为这实际上是一个问题 【参考方案1】:
<?php
session_start();
include "pconfig.php"; // Using database connection file here


$id = $_GET['id']; // get id through query string

if($_SESSION["id"]!==$id)// display error message if user is not same
    echo "You need to delete your own record"; 
    exit; 


$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;
?>

你需要在删除页面的上面添加session_start()函数

使用您在登录页面中指定的 $_SESSION["id"] 会话 在执行任何操作之前始终检查/比较逻辑,这样您的代码将保持小巧、智能、简单、可读和快速。

【讨论】:

以上是关于如何让用户只删除他们的详细信息而没有其他人的php的主要内容,如果未能解决你的问题,请参考以下文章

如何在php中隐藏/保护密码详细信息?

如何允许用户登录更新/编辑他们的个人资料设置/信息

PHP删除Redis所有数据

通过存储用户凭据在 php 中集成 Paypal

JS & PHP - 如果其他字段已填写,则更改下拉值

带有表单验证的表单提交预览 (PHP)