Php forms are added with Token to prevent repeated submission of method analysis, form token

Source: Internet
Author: User

Php forms are added with Token to prevent repeated submission of method analysis, form token

This example describes how to add a Token to a php form to prevent repeated submission. We will share this with you for your reference. The details are as follows:

Token

Token is a Token. Its biggest feature is randomness and unpredictable. Generally, hackers or software cannot guess.

So what is the function of Token? What is the principle?

Token is generally used in two places-to prevent repeated form submission and anti-csrf attacks (Cross-Site Request Forgery ).

Both are implemented by session token in principle. When the client requests a page, the server generates a random number Token, places the Token in the session, and sends the Token to the client (generally by constructing the hidden form ). The next time the client submits a request, the Token will be submitted to the server along with the form.

Then, if it is applied to the "anti csrf attack", the server will verify the Token value to determine whether it is equal to the Token value in the session. If it is equal, the request is valid, not forged.

However, if it is applied to "prevent repeated form submissions", after the server verifies the same Token for the first time, it will update the Token value in the session. If the user submits the Token repeatedly, the second verification fails because the Token in the form submitted by the user has not changed, but the Token in the server session has changed.

The preceding session application is relatively secure, but also cumbersome. When multiple pages and requests are sent, multiple tokens must be generated at the same time, which consumes more resources and reduces execution efficiency. Therefore, session tokens can also be replaced by cookie storage verification information. For example, when "repeated submission" is required, after the first submission, the submitted information is written to the cookie. When the second submission, because the cookie already has a submission record, therefore, the second submission fails.

However, cookie storage has a critical weakness. If the cookie is hijacked (xss attacks can easily obtain the user cookie), then gameover again. Hackers will launch csrf attacks directly.

Therefore, it is safe and efficient. Take specific measures.

Php forms are added with Token to prevent repeated submission

The principle is to generate a random string and put it in the session. Submitting a form and then verifying the string can prevent others from writing a form to cheat the submission, submitting the string repeatedly, or double-click the submission.

The simple code implemented using php is as follows:

<? Php/** PHP simply uses token to prevent repeated submission of forms * This processing method is purely for beginners to refer to */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 the token is empty, a tokenif (! Isset ($ _ SESSION ['Token']) | $ _ SESSION ['Token'] = '') {set_token ();} if (isset ($ _ POST ['test']) {if (! Valid_token () {echo "token error";} else {echo 'submitted successfully, 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 above method is simpler, and the following code is 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 = 32, $md5 = true) {  # Seed random number generator  # Only 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',    '&',    '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 ($md5) {    # Number of 32 char chunks    $chunks = ceil(strlen($token) / 32);    $md5token = '';    # Run each chunk through md5    for ($i = 1; $i <= $chunks; $i++)      $md5token .= md5(substr($token, $i * 32 - 32, 32));    # Trim the token    $token = substr($md5token, 0, $len);  }  return $token;}?>

Form. php

<? Phpinclude_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 and so on --> </form>

Action. php

<? Phpsession_start (); if ($ _ POST ['Token'] ==$ _ SESSION ['Token']) {unset ($ _ SESSION ['Token']); echo "this is a normal request";} else {echo "this is an invalid request";}?>

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.