Announcement Announcement Module
Collapse
No announcement yet.
Protect form data using token generation Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Protect form data using token generation

    The first thing that we are going to do is generate a "token", essentially a secret code. This token is going to store in a session variable. This token also is going to be applied as a hidden input on the form itself when it is first generated in the browser. That means this token exists both on the client side and the server side and we can match them when the form gets submitted and make sure they are the same. What this does is ensure that any submission of the form is our form and not some third-party script wailing away at us from a different server.
    First we'll need to start a session, then We'll build the token and assign it to the session variable, and return it for our use.

    Code:
    // Start a session
    session_start();
    
    // generate a token from an unique value and write the generated token to the session variable field when the form is sent.
    $_SESSION['form_token'] = md5(uniqid(microtime(), true));
    The unique value here comes from a md5 hash of the microtime function.

    Then put the token as a hidden input in the <form> element:

    Code:
    <input type="hidden" name="token" value="<?php echo $_SESSION['form_token']; ?>">
    Then you can check the token values after the form is submitted.


    Code:
    // check if a session is started and a token is transmitted, if not return an error
    if(!isset($_SESSION['form_token'])) {
    echo "Hack-Attempt found! Access denied.";
    exit;
    }
    
    // check if the form is sent with token in it
    if(!isset($_POST['token'])) {
    echo "Hack-Attempt found! Access denied.";
    exit;
    }
    
    // compare the tokens against each other if they are still the same
    if ($_SESSION['form_token'] !== $_POST['token']) {
    echo "Hack-Attempt found! Access denied.";
    exit;
    }

    This code above checks to see if the token exists in both required places and that they match. If all those three things are true, the function returns true, if not, it returns false.
    Now we check that value before proceeding.

    Hope I helped here.

    Happy coding.
Tag Cloud Tag Cloud Module
Collapse
Working...
X