php Method to Prevent Remote Submission of Forms Outside Station

  • 2021-07-21 08:07:27
  • OfStack

This article describes the example of php to prevent the remote submission of forms outside the station, and shares it with you for your reference. The specific implementation method is as follows:

Generally speaking, preventing webmasters from submitting forms is nothing more than adding an token to verify every time they open forms or submit data. This is actually no different from the verification code practice. Let's take a look at some examples of preventing remote submission of forms outside the station.

Example 1: Every time we open the submission page, we generate an token and save it in session. When the form is submitted, we will judge whether the current token value and session are 1. If yes, it is normal submission, otherwise it is 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 also a more obvious way is to use the verification code, the way of this verification code and other ways is a kind of oh, look at a simple example below

Example 2: Adding verification code

Adding verification code when submitting forms can effectively prevent the emitter from submitting data. However, as the graphics and image recognition program becomes more powerful, the verification code recognition is constantly improving its difficulty. Some verification codes even add voice recognition, and some small sites can adopt this way.

if($_POST['vcode'] != get_vcode())
{
    exit(' Verification code verification failed and cannot be put into storage ');
}

Specific examples interested readers can find many relevant examples of verification on the Internet.

I hope this article is helpful to everyone's PHP programming.


Related articles: