我正在制作一个表单,我想让提交的 PHP 页面仅在提交表单时才可访问,从而防止对我的 PHP 页面的自定义请求。
这是我的 form.html:
<html>
<head>
<title>Name/Surname form</title>
</head>
<body>
<form id="form1" method="POST" action="processData.php">
Name: <input type="text" id="name" name="name"><br>
Surname: <input type="text" id="surname" name="surname"><br>
<input type="submit" value="Submit form">
</form>
</body>
</html>
然后是我的 processData.php:
<?php
if(!isset($_POST['name'],$_POST['surname'])) die;
include ("config.php");
//connect
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname); //variables from config.php
//check connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($stmt = $mysqli->prepare("INSERT INTO name_surname_table (name, surname) values (?, ?)")) {
//bind
$stmt->bind_param('ss', $name, $surname);
//set
$name=$_POST['name'];
$surname=$_POST['surname'];
//execute
$stmt->execute();
//close
$stmt->close();
}
else {
//error
printf("Prepared Statement Error: %s\n", $mysqli->error);
}
?>
问题是,如果我在没有提交上一页中的表单的情况下执行自定义发布请求,数据将提交到数据库,这意味着自动化程序可以将它想要的任何内容放入我的数据库中......如何我可以阻止这种情况吗?
谢谢!
最佳答案
您有很多选项可以防止机器人自动提交您的表单:
token 可以像这样完成:
session_start();
//generate a unique string
$token = uniqid(rand(), true);
//Store the token
$_SESSION['token'] = $token;
//Store the token_time
$_SESSION['token_time'] = time();
向您的表单添加一个隐藏的输入:
<input type="hidden" name="token" id="token" value="<?php echo $token;?>"/>
与将表单提交到数据库之前相比:
session_start();
//If token exists
if(isset($_SESSION['token']) && isset($_SESSION['token_time']) && isset($_POST['token']))
{
//If it's the same as the posted one
if($_SESSION['token'] == $_POST['token'])
{
//For example 15 mins ago
$old_time = time() - (15*60);
//If token hasn't expired
if($_SESSION['token_time'] >= $old_time)
{
//Do your queries here
}
}
}
关于php - 如何防止自定义发布请求到表单的 "action"页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448568/