编程语言
首页 > 编程语言> > php-如何防止自定义发布请求到表单的“操作”页面

php-如何防止自定义发布请求到表单的“操作”页面

作者:互联网

我正在制作一个表单,我想使提交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);
    }
?>

问题是,如果我在不提交上一页中的表单的情况下进行自定义发布请求,则数据将提交到db,这意味着自动化程序可以将所需的任何内容都放入db中.如何防止这个?

谢谢!

解决方法:

您有很多选择可以防止机械手自动提交表单:

>使用Captcha或一些简单的计算字段(例如,给出3 2的是什么?)
>带令牌
>用$_REQUEST变量进行检查

令牌可以像这样完成:

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

标签:form-submit,html,php
来源: https://codeday.me/bug/20191031/1973351.html