gpt4 book ai didi

javascript - 当未通过单击按钮引用时,如何阻止对 URL 的直接访问?

转载 作者:行者123 更新时间:2023-12-01 00:06:20 25 4
gpt4 key购买 nike

我有一个本地站点,其中第二页只能通过特定按钮访问,而不能通过编写 URL 直接访问。

我有这个简单的例子:

第 1 页:

<html>
<head><title>page 1</title></head>
<body>
<button type="button"><a href="page2.html">to page 2</a></button>
</body>
</html>

第 2 页:

<html>
<head><title>page 2</title></head>
<body>
<h1>PAGE 2</h1>
</body>
</html>

谢谢。

最佳答案

您不想依赖 HTTP Referer header 来执行此操作,因为它很容易伪造。客户端可以简单地随请求一起发送引用 header ,即使他们从未加载第一页。

要实现此目的,您需要生成一个唯一的 token (只有您的服务器和客户端知道),并要求第二个页面接收此 token 才能加载该页面。

例如:

<?php
function generateToken() {
return base64_encode(random_bytes(64));
}

session_start(); // start a session to store this token
$_SESSION['token'] = generateToken(); // store the token temporarily in the session
// you can also store it in your database or in memcached if you prefer
?>
<html>
<head><title>page 1</title></head>
<body>
<button type="button">
<a href="page2.php?token=<?=htmlspecialchars($_SESSION['token'])?>">
to page 2
</a>
</button>
</body>
</html>

现在第二页需要验证此 token 是否正确。

<?php
session_start(); // load the session data
if (empty($_SESSION['token']) ||
empty($_GET['token']) ||
$_GET['token'] !== $_SESSION['token'])
{
echo "You did not reach this page by the link from page1!";
exit; // stop the page from loading
}
?>
<html>
<head><title>page 2</title></head>
<body>
<h1>PAGE 2</h1>
</body>
</html>

关于javascript - 当未通过单击按钮引用时,如何阻止对 URL 的直接访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60358031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com