在PHP 8中预防跨站点请求伪造(CSRF)涉及实施强大的机制以验证启用您的应用程序,而不是来自您的应用程序,而不是来自恶意的第三方站点。最有效的方法是使用同步令牌。这涉及为每个用户会话生成独特的,不可预测的令牌,并将其嵌入到服务器的表格中。收到表单提交后,服务器然后验证提交的令牌是否与存储在用户会话中的令牌匹配。如果它们不匹配,则该请求将被拒绝为潜在的欺诈性。
这是您可以在PHP 8:
Random_bytes()
功能是理想的选择。使用 $ _会话
。
csrf_token
(或类似的描述性名称)。 $ _ post post post [csrf_token'''csrf_token'' (<code> $ _会话['csrf_token']
)。比较两个。如果它们是相同的,则该请求可能是合法的。如果不是,请拒绝请求并显示错误消息。
<pre class="brush:php;toolbar:false"> <code class="“" php>&lt;?php session_start(); //在第一页加载上生成CSRF令牌,如果(!isset($ _ session ['csrf_token'])){$ _session ['csrf_token'] = bin2hex(rando_bytes(32)); } //示例形式echo; form; form'form method ='post'action ='process.php'&gt;&quot;&quot;; echo&quot&lt; input type ='隐藏'name ='csrf_token'value ='{$ _ session ['csrf_token']}'}'&gt;&quot;&quot;; echo&quot&lt; input type ='submit'value ='submit'&gt;&quot;; echo&quot&lt;/form&gt;&quot; // process.php session_start(); if($ _server ['request_method'] ==='post'){if(isset($ _ post ['csrf_token']))&amp;&amp;&amp;&amp;&_post ['csrf_token'========= $ _session [ ... unset($ _ session ['csrf_token']); //使用后删除令牌的好练习} else {//拒绝请求-CSRF攻击检测到DIE(“检测到CSRF攻击检测到!”); } } ?></code>
Remember to always use HTTPS to prevent interception of the token.
Beyond simply using synchronizer tokens, several best practices enhance CSRF protection:
HttpOnly
flag for the CSRF cookie。这样可以防止客户端的JavaScript访问cookie,从而使攻击者更难窃取令牌。 secure> Secure
flag for csrf cookie确保仅通过https和https trals transerm off https。即使它们不直接参与CSRF保护机制。这有助于防止其他漏洞与CSRF攻击结合使用。可以将CSRF整合到现有项目中。 Focus on high-risk forms first (those that perform critical actions like changing passwords, making financial transactions, or updating user profiles).
以上是如何防止PHP 8中的跨站点伪造(CSRF)?的详细内容。更多信息请关注PHP中文网其他相关文章!