title: csrf Token class
body: <p>can someone explain me how to protect the profile page from the wrong user editing the URL to see some other users profile page. i am using a token class to generate a random number to protect against Cross Site Request Forgery. for some reason it doesn't work any suggestion or other way to do that </p>
  
  <p>Also i get the following error : Undefined index: token in PhpProject22_CSRF\profile.php on line 12</p>
  
  <pre><code>&lt;?php 
  session_start();
  require_once 'Classes/Token.php';
  $tk = new Token();
  
  if(isset($_POST['username'],$_POST['product'],$_POST['token'])){
  $username = $_POST['username'];
  $product = $_POST['product'];
  if(!empty($product) &amp;&amp; !empty($username)){
      if(Token::check($_POST['token'])){
          echo $_POST['token'].'&lt;br&gt;';
          $tk-&gt;get('username');
          $_SESSION['user'] = $tk-&gt;name();
          echo 'Process Order';
      }
  }
  }
  ?&gt;
  
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
      &lt;title&gt;CSRF Protection&lt;/title&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;form action="" method="POST"&gt;
          &lt;div class="product"&gt;
              &lt;strong&gt;Profile&lt;/strong&gt;
              &lt;div class='field'&gt;
                  Username: &lt;input type='text' name='username'&gt;
              &lt;/div&gt;
              &lt;input type='submit' value='Order'&gt;
              &lt;input type='hidden' name='product' value='1'&gt;
              &lt;input type='hidden' name='token' value='&lt;?php echo Token::generate();?&gt;'&gt;
          &lt;/div&gt;
      &lt;/form&gt;
      &lt;?php
      if(isset($_POST['username'])){
      ?&gt;
      &lt;p&gt;Hello &lt;a href = 'profile.php?user=&lt;?php echo $tk-&gt;name();?&gt;'&gt;&lt;?php echo $tk-  &gt;name();?&gt;&lt;/a&gt;!&lt;/p&gt;
      &lt;?php
      }
      ?&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  
  &lt;?php
  class Token{
  private $_data;
  
  public static function generate(){
      return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
  }
  
  public static function check($token){
      if(isset($_SESSION['token']) &amp;&amp; $token === $_SESSION['token']){      
          unset($_SESSION['token']);
          return true;
      }
      return false;
  }
  
  public function get($item){
      if(isset($_POST[$item])){
          $this-&gt;_data = $_POST[$item];
      }
  }
  
  public function name(){
  return $this-&gt;_data;
  }
  }
  ?&gt;
  
  &lt;?php
  require_once 'Classes/Token.php';
  session_start();
  ?&gt;
  &lt;form action="" method="POST"&gt;
  &lt;input type='hidden' name='token' value='&lt;?php echo Token::generate();?&gt;'&gt;
  &lt;/form&gt;
  
  &lt;?php
  echo 'Hello '.$_SESSION['user'].'!&lt;br&gt;';
  if(isset($_GET['user'])){
  if(Token::check($_POST['token'])){
      echo $_GET['user'];
  }
  }
  ?&gt; 
  </code></pre>