PHP form Add token Prevent duplicate Submit method analysis _php Tips

Source: Internet
Author: User
Tags md5 php database php form php introduction csrf attack

This example describes the way PHP forms are added to token prevent duplicate submissions. Share to everyone for your reference, specific as follows:

A brief talk on token

Token, is a token, the biggest feature is randomness, unpredictable. General hackers or software can not be guessed out.

So, what's the role of token? What is the principle?

Token is typically used in two places-preventing form recurrence, anti CSRF attacks (Cross-site request forgery).

Both in principle are through the session token to achieve. When a client requests a page, the server generates a random number token and places the token in session, then sends the token to the client (typically by constructing hidden forms). The next time the client submits the request, the token is committed to the server side as the table is single.

Then, if applied to "anti CSRF attack", then the server side will verify the token value, whether it is equal to the token value in the session, and if it is equal, it can prove that the request is valid and not forged.

However, if applied to prevent form repeat submission, the first time the server side verifies the same, the token value in the astringent session is updated, and if the user commits repeatedly, the second validation will fail because the token in the user's submitted form does not change, But token has changed in server-side session.

The above session application is relatively safe, but also called cumbersome, and when multiple-page multiple requests, you must adopt a multiple token method, so that more resources to occupy, execution efficiency will be reduced. Therefore, you can also use cookies to store authentication information instead of Session Token. For example, when a "duplicate submission" is made, the submitted information is written to the cookie after the first submission, and the second commit fails because the cookie already has a commit record.

However, Cookie storage has a fatal weakness, and if the cookie is hijacked (XSS attacks are easy to get user cookies), then another gameover. Hackers will directly implement CSRF attacks.

So, safe and efficient relative. Specific issues to deal with it.

PHP form Join token prevent duplicate submissions

The principle is to generate a random string in the session, submit the form later to verify the string, you can do to prevent others to write the form to deceive the submission, repeated submissions or double click to submit.

The simple code implemented in PHP is as follows:

<?php
*
* php Simple use of token to prevent form recurrence
* This approach is purely for beginners reference
/session_start ();
function Set_token () {
  $_session[' token '] = MD5 (Microtime (true));
function Valid_token () {
  $return = $_request[' token '] = = = $_session[' token ']? true:false;
  Set_token ();
  return $return;
}
If token is empty, generates a token if
(!isset ($_session[' token ')) | | $_session[' token ' the]== ') {
  set_token ();
}
if (isset ($_post[' test ')) {
  if (!valid_token ()) {
    echo "token error";
  } else{
    Echo ' successfully submitted, 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= "Submit"/>
</form>

The simpler method above, the following code is a little more secure.

token.php

<?php/* Created on 2013-3-25 * * To change the template for this generated file go to * window-preferences- Phpeclipse-php-code Templates/function GetToken ($len = $md 5 = true) {# Seed random number generator # ONL
  Y needed for PHP versions prior to 4.2 Mt_srand (double) microtime () * 1000000); 
    # array of characters, adjust as desired $chars = Array (' Q ', ' @ ', ' 8 ', ' y ', '% ', ' ^ ', ' 5 ',
    ' Z ', ' (', ' G ', ' _ ', ' O ', ' ', ' S ', '-', ' N ', ' < ', ' D ', ' {', '} ', ' [', '] ', ' h ', '; ', ' W ', '. ', '/', ' | ', ': ', ' 1 ', ' E ', ' L ', ' 4 ', ' &
    amp; ', ' 6 ', ' 7 ', ' # ', ' 9 ', ' A ', ' a ', ' B ', ' B ', ', ', ' C ', ' d ', ' > ',
    ' E ', ' 2 ', ' f ', ' P ', ' g ', ', ', ', ', ', ', ', ', ' H ', ' I ', ' X ', ' U ', ' J ', ' K ', ' R ', ' L ', ' 3 ', ' t ', ' M ', ' n ', ' = ', ' o ', ' + ', ' P ', ' F ', ' Q ', '! ', ' K ', ' R ', ' s ', ' C ', ' m ', ' T ', ' V ', ' j ',
  ' U ', ' V ', ' w ', ', ', ' X ', ' I ', ' $ ', ' Y ', ' z ', ' * ';
  # Array Indice friendly number of chars;
  $numChars = count ($chars)-1;
  $token = '; # Create Random token at the specified length for ($i = 0; $i < $len; $i + +) $token. = $chars [Mt_rand (0, $numChars
  )];
  # Should token be run through MD5?
    if ($MD 5) {# Number of char chunks $chunks = Ceil (strlen ($token)/32);
    $MD 5token = '; # Run each chunk through MD5 for ($i = 1; $i <= $chunks; $i + +) $MD 5token. = MD5 (substr ($token, $i * 32-32,
    32));
  # Trim The token $token = substr ($md 5token, 0, $len);
return $token;

 }?>

form.php

<?php
include_once ("token.php");
$token = GetToken ();
Session_Start ();
$_session[' token ' = $token;
? >
<form action= "action.php" method= "Post <input type=" hidden "name=" token "value="
<?= $token? > "/>
<!--Other input submit-->
</form>

action.php

<?php
session_start ();
if ($_post[' token '] = = $_session[' token ']) {
  unset ($_session[' token ']);
  echo "This is a normal submit request";
else{
  echo "This is an illegal submission request";
>

More about PHP Interested readers can view the site topics: "PHP Design Security Course", "PHP Security Filtering Skills Summary", "PHP operation and operator Usage Summary", "PHP Network Programming Skills Summary", "PHP basic Grammar Introductory Course", " PHP Operations Office Document Tips summary (including word,excel,access,ppt), "PHP Introduction to Object-oriented Programming", "PHP string (String) Usage Summary", "Php+mysql Database Operations Introductory Tutorial" and " A summary of common PHP database operations tips

I hope this article will help you with the PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.