1
votes

I was reading up on some PHP PDO data sanitization, and came accross this post:

PDO & Sanitize Date/Remove HTML

I'm confident that my code uses PDOStatement bindParam to prevent SQL Injections, However i read this comment ( paraphrased )

'using $_POST with tokens will help to avoid CSRF'

and I am curious, what is meant by a token and how do I implement it?

1
@Melvin OP asked a very specific question and all you can provide is a LMGTFY for "CSRF" hidden behind a URL shortening service? - brezanac
CRSF is a very specific topic, searching google would give you not only in-depth information but also tutorials on how to protect your forms. The poster is just curious on how to implement it, he is not having any troubles actually implementing it, which is exactly the kind of information you can find on the internet very easily yourself. Take wikipedia for example, im sure it'll be in the top 3 in the search results and it covers almost everything you need to know to understand the concept behind CSRF. I also just could've dropped a wikipedia link here but i think this was more appropriate. - Melvin
My question was more along the lines of 'What is a token', not really about CRSF - AlexMorley-Finch
If you understand the idea behind CRSF then you know a token can be anything you want as long as it has some kind of randomness in it. A token does not need to be cryptographly secure as it does not contain any sensitive information. - Melvin

1 Answers

0
votes

A token may be some hash, you store it in a session and also send it with via the form. Before validating the form-data you check if:

  1. a token has been sended and
  2. the token is stored in the session

A simple implementation:


<?php
  session_start();
  if(!isset($_SESSION['token']))
  {
    $_SESSION['token']=uniqid();
  }
?>

<form method="post">
    <input name="token" type="hidden" value="<?php echo $_SESSION['token'];?>">
    <input name="something"  value="some data to send">
    <input type="submit">
</form>

<?php
  if(isset($_POST['something']))
  {
    if(!isset($_POST['token']) || $_POST['token']!==$_SESSION['token'])
    {
      echo 'missing a valid token';
    }
    else
    {
      echo 'got a valid token, I will use the data';
    }
  }
?>