gpt4 book ai didi

php - 防止用户编辑彼此的条目

转载 作者:行者123 更新时间:2023-11-29 22:15:56 24 4
gpt4 key购买 nike

我有一个 PHP 脚本,允许用户将条目注册到数据库中。条目自动递增。我发现,用户 #A 可以通过将 url 从 edit.php?id=2 更改为 id=1 来从用户 #B 获取条目。

我当然想阻止这种情况发生。所以我的想法是:如果 mysql 条目中的用户 ID 字段与我的 php 脚本中的 $_SESSION['user_id'] 匹配,则允许编辑。

用户应该只能编辑他们自己发布的条目。

实现这一目标的最佳和最有效的方法是什么?

<?php $bruker = $_SESSION['user_id']; ?>

<?php }
/*
EDIT RECORD
*/
// if the 'id' variable is set in the URL, we know that we need to edit a record
if (isset($_GET['id']))
{
// if the form's submit button is clicked, we need to process the form
if (isset($_POST['submit']))
{
// make sure the 'id' in the URL is valid
if (is_numeric($_POST['id']))
{
// get variables from the URL/form
$id = $_POST['id'];
$elv = htmlentities($_POST['elv'], ENT_QUOTES);
$vald = htmlentities($_POST['vald'], ENT_QUOTES);
$art = htmlentities($_POST['art'], ENT_QUOTES);
$dato = htmlentities($_POST['dato'], ENT_QUOTES);
$vekt = (int)$_POST['vekt'];
$lengde = (int)$_POST['lengde'];
$flue = htmlentities($_POST['flue'], ENT_QUOTES);
$gjenutsatt = (int)$_POST['gjenutsatt'];
$kjonn = (int)$_POST['kjonn'];
$bilde = htmlentities($_POST['bilde'], ENT_QUOTES);
$user = $_SESSION['user_id'];

// check that required fields are not empty
if ($elv == '' || $vald == '' || $art == '' || $dato == '' || $vekt == '' || $kjonn == '')
{
// if they are empty, show an error message and display the form
$error = 'Du må fylle ut de påkrevde feltene!';
renderForm($elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $error, $id);
}
else
{
// if everything is fine, update the record in the database
if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art = ?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?, bilde = ?, user = ?
WHERE id=?"))
{
$stmt->bind_param("ssssiisiisii", $elv, $vald, $art, $dato, $vekt, $lengde, $flue, $gjenutsatt, $kjonn, $bilde, $user, $id);
$stmt->execute();
$stmt->close();
}
// show an error message if the query has an error
else
{
echo "ERROR: could not prepare SQL statement.";
}

// redirect the user once the form is updated
header("Location: /");
}
}
// if the 'id' variable is not valid, show an error message
else
{
echo "Error!";
}
}
// if the form hasn't been submitted yet, get the info from the database and show the form
else

最佳答案

假设您的用户具有唯一的 ID,您只需向 SQL 添加额外的 WHERE 子句即可:

if ($stmt = $mysqli->prepare("UPDATE fisk SET elv = ?, vald = ?, art = ?, dato = ?, vekt = ?, lengde = ?, flue = ?, gjenutsatt = ?, kjonn= ?, bilde = ?, user = ? WHERE id=? AND created_user = ?"))

显然,将 created_user 替换为用于存储创建该条目的用户 ID 的列。

这样它只会更新由用户尝试编辑它创建的行。

更安全的是,您可以通过首先查询相关行的创建用户 ID,然后按照您的建议根据您的用户 ID $_SESSION 检查它,然后终止脚本或在脚本执行之前重定向它们,从而防止他们看到该页面进入查询。

关于php - 防止用户编辑彼此的条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31210296/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com