rodrigobertin
9/23/2015 - 12:44 AM

Class token

Class token

/**
 * Class Token
 */
class Token
{

  /**
   * Crear el token en session
   * @return string
   */
  function createToken()
  {
    $token = md5(uniqid(rand(), TRUE));;
    $_SESSION['token'] = $token;
    $_SESSION['token_time'] = time();
    return $token;
  }

  /**
   * Destruir el token
   * @return bool
   */
  function destroyToken()
  {
    $_SESSION['token'] = null;
    $_SESSION['token_time'] = null;
    return true;
  }

  /**
   * Token en form
   * @return string
   */
  function tokenForm()
  {
    $token = $_SESSION['token'];
    echo '<input type="hidden" id="token" name="token" value="' . $token . '">';
  }

  /**
   * Returns true if user-submitted POST token is
   * identical to the previously stored SESSION token.
   * Returns false otherwise.
   */
  function tokenIsValid()
  {
    if (isset($_POST['token'])) {
      $user_token = $_POST['token'];
      $stored_token = $_SESSION['token'];

      //si no es valido
      if ($user_token != $stored_token) {
        echo 'No permitido';
        exit();
      }

    } else {
      echo 'No token';
      exit();
    }
  }

  /**
   * Optional check to see if token is also recent
   * @return bool
   */
  function csrf_token_is_recent()
  {
    $max_elapsed = 60 * 60 * 24; // 1 day

    if (isset($_SESSION['token_time'])) {
      $stored_time = $_SESSION['token_time'];
      return ($stored_time + $max_elapsed) >= time();

    } else {
      // Remove expired token
      self::destroyToken();
      @session_destroy();
      return false;
    }
  }

}