1

我有一个投票脚本。它运作良好。

但我有一个小问题。我不希望人们直接到达投票提交页面(投票提交到数据库的页面)。我希望他们只能通过特定链接访问它。

我的投票链接:

<form>
<INPUT id="voteup1" type="BUTTON" VALUE="Vote it up!" ONCLICK="window.location.href='rankup.php?rankid=<? echo $id1; ?>'"> 
<INPUT id="votedown1" type="BUTTON" VALUE="Vote it down!" ONCLICK="window.location.href='rank.php?rankid=<? echo $id1; ?>'"> 
</form>

$id1用于定义用户投票的页面。(投票添加到数据库时很重要)

我不希望人们直接到达 rankup.php 和 rank.php。我怎么能防止这种情况?

4

3 回答 3

3

HTTP 是无状态的。没有“直接/间接”到达页面 - 每个请求都与之前的请求断开连接。

PHP 有一种机制来克服这个限制:Sessions,它反过来使用 cookie。

因此,您可以在您拥有投票按钮的页面上设置一个会话变量,用作标志:“can-vote-now”,如果未设置,则禁止投票。

带有按钮的页面上的伪代码:

set_voting_variable_for($poll_identifier);

rankup.php 上的伪代码:

if (!is_voting_variable_set($poll_identifier)) {
  // redirect away
} else {
  // register the vote
}

Oh, and note that pages that make things happen (so-called "non-idempotent" actions - e.g. increase vote count) shouldn't be reachable via GET (as GET is reserved for showing things without changing them - "idempotent" actions): you may want to make a form which uses POST instead.

于 2011-09-07T16:16:08.893 回答
2

最好的办法是使用 cookie。仅允许使用您在特定时间范围内生成的 cookie 值进行投票。否则,很容易生成 cookie 值。

您可以使用 PHP 会话轻松完成此操作。

您还应该知道,GET不建议对请求执行操作(更改投票计数)。 GET只有在检索具有特定参数的数据时才应使用变量。改为使用POST。否则,每当一些搜索机器人偶然发现你的投票脚本时,投票就会改变。

于 2011-09-07T16:15:34.047 回答
1

You could use PHP's referrer variable $_SERVER['HTTP_REFERER'] to check that the referring URL belongs to you. But you can't rely on this 100% because this information may not be sent, and as it's part of the HTTP header the user can modify it if they like.

Sessions, as suggested, may be a good way to go about doing this. I'd choose sessions over cookies because users can disable their cookies on your site - and cookies are editable by the users. Sessions can only be edited by someone with access to your server (shared hosting usually).

Also I disagree with the way that you're doing this. Currently you're relying on user's having JavaScript enabled in their browsers. Some users don't have it enabled, some user's browsers don't support it. Some users even disable page redirects like that.

Personally, rather than using two scripts, I'd use a single script something like:

<form action="rank.php" method="post">
<input type="submit" value="Vote up!" />
<input type="submit" value="Vote down!" />
</form>

In rank.php you detect which of the two buttons was pressed then run a function accordingly. You could use a session variable to store the ID of the item they'll be voting on and then read that ID from the session (make sure to escape it though) to ensure the ID can't be changed by the user at the last minute.

Hopefully that should give you some ideas.

于 2011-09-07T16:34:18.477 回答