Token is a token. Its biggest feature is randomness and unpredictability.
Token is generally used in two places - to prevent repeated form submissions and anti-csrf attacks (cross-site request forgery).
Both are implemented in principle through session token
. When the client requests a page, the server will generate a random number Token, place the Token in the session, and then send the Token to the client (usually by constructing a hidden form). The next time the client submits a request, the Token will be submitted to the server along with the form.
If applied to "prevent repeated form submission", after the first verification is the same on the server side, the Token value in the session will be updated. If the user submits repeatedly, the second verification judgment will fail because The Token in the form submitted by the user has not changed, but the Token in the server-side session has changed.
Online video tutorial sharing: php video tutorial
Add Token to the php form to prevent repeated submissions
The principle is to generate a random The string is placed in the session. This string is verified after submitting the form. This can prevent others from writing the form themselves to cheat the submission, repeat submission or double-click submission.
Simple implementation (for reference only):
<?php /* * PHP简单利用token防止表单重复提交 * 此处理方法纯粹是为了给初学者参考 */ session_start(); function set_token() { $_SESSION['token'] = md5(microtime(true)); } function valid_token() { $return = $_REQUEST['token'] === $_SESSION['token'] ? true : false; set_token(); return $return; } //如果token为空则生成一个token if(!isset($_SESSION['token']) || $_SESSION['token']=='') { set_token(); } if(isset($_POST['test'])){ if(!valid_token()){ echo "token error"; }else{ echo '成功提交,Value:'.$_POST['test']; } } ?> <form method="post" action=""> <input type="hidden" name="token" value="<?php echo $_SESSION['token']?>"> <input type="text" name="test" value="Default"> <input type="submit" value="提交" /> </form>
Recommended related article tutorials: php tutorial
The above is the detailed content of How to prevent repeated submission of forms in php. For more information, please follow other related articles on the PHP Chinese website!