有人可以解释我如何保护配置文件页面免于错误的用户编辑URL以查看其他用户个人资料页面。我正在使用令牌类生成一个随机数,以防止跨站点请求伪造。由于某种原因,它没有任何建议或其他方式来做到这一点
我也收到以下错误:第12行的PhpProject22_CSRF \ profile.php中的未定义索引:令牌
<?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) && !empty($username)){
if(Token::check($_POST['token'])){
echo $_POST['token'].'<br>';
$tk->get('username');
$_SESSION['user'] = $tk->name();
echo 'Process Order';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>CSRF Protection</title>
</head>
<body>
<form action="" method="POST">
<div class="product">
<strong>Profile</strong>
<div class='field'>
Username: <input type='text' name='username'>
</div>
<input type='submit' value='Order'>
<input type='hidden' name='product' value='1'>
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</div>
</form>
<?php
if(isset($_POST['username'])){
?>
<p>Hello <a href = 'profile.php?user=<?php echo $tk->name();?>'><?php echo $tk- >name();?></a>!</p>
<?php
}
?>
</body>
</html>
<?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']) && $token === $_SESSION['token']){
unset($_SESSION['token']);
return true;
}
return false;
}
public function get($item){
if(isset($_POST[$item])){
$this->_data = $_POST[$item];
}
}
public function name(){
return $this->_data;
}
}
?>
<?php
require_once 'Classes/Token.php';
session_start();
?>
<form action="" method="POST">
<input type='hidden' name='token' value='<?php echo Token::generate();?>'>
</form>
<?php
echo 'Hello '.$_SESSION['user'].'!<br>';
if(isset($_GET['user'])){
if(Token::check($_POST['token'])){
echo $_GET['user'];
}
}
?>
答案 0 :(得分:3)
查看帖子时,您需要执行以下操作:
if($_POST){
if(isset($_POST['token']) && Token::check($_POST['token']){
code
}else{
error
}
}
如果有人欺骗帖子,并且不包含令牌,那么您将获得未定义的索引错误,因为$ _POST ['token']不存在而您正在引用它。