Generally speaking, preventing form submission outside the site is nothing more than adding a token for verification every time the form is opened or data is submitted. This is actually no different from the verification code method. Let’s look at a few examples of preventing remote submission of forms outside the site.
Example 1: Every time we open the submission page, we generate a token, and then save it in the session. When the form is submitted, we determine whether the current token value is consistent with the session. Consistent, if yes, it is a normal submission, otherwise, it is an invalid submission.
The specific code is as follows:
<?php session_start(); if ($_POST['submit'] == "go"){ //check token if ($_POST['token'] == $_SESSION['token']){ //strip_tags $name = strip_tags($_POST['name']); $name = substr($name,0,40); //clean out any potential hexadecimal characters $name = cleanHex($name); //continue processing.... }else{ //stop all processing! remote form posting attempt! } } $token = md5(uniqid(rand(), true)); $_SESSION['token']= $token; function cleanHex($input){ $clean = preg_replace("![\][xX]([A-Fa-f0-9]{1,3})!", "",$input); return $clean; } ?> <form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post"> <p><label for="name">Name</label> <input type="text" name="name" id="name" size="20" maxlength="40"/></p> <input type="hidden" name="token" value="<?php echo $token;?>"/> <p><input type="submit" name="submit" value="go"/></p> </form>
There is another obvious way, which is to use verification code. This verification code method is the same as other methods. Take a look below Simple example
Example 2: Add verification code
Adding verification code when submitting the form can effectively prevent the water filling machine from submitting data. However, as graphics and image recognition programs become more powerful, verification code recognition continues to become more difficult. Some verification codes even incorporate sound recognition. Some small sites can use this method.
if($_POST['vcode'] != get_vcode()) { exit('验证码校验失败,无法入库'); }
The above content is for reference only!
Recommended tutorial: PHP video tutorial
The above is the detailed content of How to prevent remote commit in PHP. For more information, please follow other related articles on the PHP Chinese website!