title: How to properly add cross-site request forgery (CSRF) token using PHP
body: <p>I am trying to add some security to the forms on my website. One of the forms uses AJAX and the other is a straightforward &quot;contact us&quot; form. I'm trying to add a CSRF token. The problem I'm having is that the token is only showing up in the HTML &quot;value&quot; some of the time. The rest of the time, the value is empty. Here is the code I am using on the AJAX form:</p>
  <p>PHP :</p>
  <pre class="lang-php prettyprint-override"><code>if (!isset($_SESSION)) {
      session_start();
      $_SESSION['formStarted'] = true;
  }
  
  if (!isset($_SESSION['token'])) {
      $token = md5(uniqid(rand(), TRUE));
      $_SESSION['token'] = $token;
  }
  </code></pre>
  <p>HTML :</p>
  <pre class="lang-html prettyprint-override"><code>&lt;input type=&quot;hidden&quot; name=&quot;token&quot; value=&quot;&lt;?php echo $token; ?&gt;&quot; /&gt;
  </code></pre>
  <p>Any suggestions?</p>