doushichi3678 2013-07-24 19:32
浏览 16
已采纳

如何为php表单添加安全性

I may be going about this the wrong way. I have a php form that collects information. After submitting it displays the information for verification. Then when you submit the form it send to another php script for processing.

I want to add a token/key that gets passed from the form to the verify form to make sure both are still on my site and then from the verify form to the final php script for processing.

This looked like the answer: How do I provide more security for checking source of the request

But I can't get it to work and I don't have enough reputation to comment. So out of pure frustration I am posting i here as a duplicate with my question.

The answer says to use this in the form:

<?php
    session_start();
    $csrfToken = md5(uniqid(mt_rand(),true)); // Token generation updated, as suggested by The Rook. Thanks!

    $_SESSION['csrfToken'] = $token;
?>
<form action="formHandler.php">
   <input type="hidden" name="csrfKey" value="<?php echo $csrfToken ?>" />
</form>

An this in the form handler:

<?php
   session_start();
   if($_POST['csrfKey'] != $_SESSION['csrfKey']) {
      die("Unauthorized source!");
   }
?>

It doesn't work. My question is shouldn't $_SESSION['csrfToken'] = $token; be $_SESSION['csrfToken'] = $csfrToken;

and shouldn't if($_POST['csrfKey'] != $_SESSION['csrfKey']) be if($_POST['csrfKey'] != $_SESSION['csrfToken'])

Although I've tried that and it doesn't work either.

I'm at a complete loss.

  • 写回答

1条回答 默认 最新

  • doushifen4060 2013-07-24 19:41
    关注

    Cleaned up the typos and name-mixing, should work like this:

    <?php
    session_start();
    $csrfToken = md5(uniqid(mt_rand(),true));
    $_SESSION['csrfToken'] = $csrfToken;
    ?>
    <form action="formHandler.php">
    <input type="hidden" name="csrfToken" value="<?php echo $csrfToken?>" />
    </form>
    

    And than when validating the submitted data:

    <?php
    session_start();
    if($_POST['csrfToken'] != $_SESSION['csrfToken']) {
      die("Unauthorized source!");
    }
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据