dongtuan1980 2014-09-20 16:34
浏览 22
已采纳

CSRF代码不起作用

I am reading a book "Essential PHP Security" by Chris Shifflet. There is a chapter on CSRF, where the author recommends using token to prevent CSRF. The code in the book says to add a token in a form we use

<?php

session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;
$_SESSION['token_time'] = time();

?>

<form action="buy.php" method="POST">
<input type="hidden" name="token" value="<?php echo $token; ?>" />
<p>
Item:
<select name="item">
    <option name="pen">pen</option>
    <option name="pencil">pencil</option>
</select><br />
Quantity: <input type="text" name="quantity" /><br />
<input type="submit" value="Buy" />
</p>
</form>

and the token can be checked with a simple conditional statement.

<?php

if (isset($_SESSION['token']) && $_POST['token']== $_SESSION['token'])
    {
        echo $_POST['token'];
        echo "form passed";
    }

But the above code does not seem to work. The "form passed" message does not shows. What is wrong with the above code?. The first set of codes generate the token but there isn't a success message.

  • 写回答

2条回答 默认 最新

  • doupo5861 2014-09-20 16:36
    关注

    You need to add session_start(); top of that codes in buy.php. Example...

    session_start();
    if (isset($_SESSION['token']) && $_POST['token']== $_SESSION['token'])
    {
        echo $_POST['token'];
        echo "form passed";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算