title: Passing token through $_SESSION and $_POST - if statement issues?
body: <p>I'm implementing CSRF protection and have had a really hard time. So I generate a token and store it in the <code>$_SESSION['token']</code>. Now I'm going to need this token for comparison on another page, so on the other page I do this: </p>
  
  <pre><code>session_start();
  $token = "";
  $token = $_SESSION['token'];
  echo $token;
  
  unset($_SESSION['token']);
  echo "&lt;br /&gt;";
  
  $compToken = "";
  $compToken = $_POST['token'];
  echo $compToken;
  </code></pre>
  
  <p>PHP requires me to set the variables to something, or else it is invalid. Here is the output to that:</p>
  
  <pre><code>41852450b2fbeed352d895d8ee57dfc9
  41852450b2fbeed352d895d8ee57dfc9
  </code></pre>
  
  <p>As you can see, they are matching tokens. Now when I come down to the if statement to compare what I just grabbed from the form before I proceed to processing: </p>
  
  <pre><code>if($compToken === $token) {
      return true;
  } else {
      echo "Token error.";
      return false;
  }
  </code></pre>
  
  <p>It just doesn't work, no errors reported either. I even tried <code>if($_SESSION['token'] === $_POST['token'])</code>, which should work since both variables were successfully passed and stored (as shown in the previous code).</p>
  
  <p>What is happening with the <code>if statement</code>?</p>
  
  <p>EDIT:</p>
  
  <pre><code>session_start();
  $token = md5(uniqid(mt_rand(), true));
  $_SESSION["token"] = $token;
  </code></pre>
  
  <p>Ok, the part below is a mess - for debugging purposes. Sorry!</p>
  
  <pre><code>session_start();
  $token = "";
  $token = $_SESSION['token'];
  $token = trim($token);
  echo $token;
  unset($_SESSION['token']);
  echo "&lt;br /&gt;";
  $compToken = "";
  $compToken = $_POST['token'];
  $compToken = trim($compToken);
  echo $compToken;
  echo "&lt;br /&gt;";
  echo"1";
  if($compToken == $token) {
      return true;
  } else {
      echo "Token error.";
      return false;
  }
  echo "2";
  </code></pre>
  
  <p>EDIT2:</p>
  
  <p>For those reading this in the future, it seems the issue was returning true for the if statement in the original <code>edit</code>. I am not sure why - but changing that to just <code>echo "true";</code> seems to work. I'm going to adjust the <code>if statement</code> to only <code>return false; and die();</code> if they do not equal each other.</p>