创建一个PHP Poll,每个IP只需一票

时间:2013-11-05 11:51:57

标签: javascript php jquery html ajax

我为我的网站用户进行了Ajax民意调查,但在我们的情况下,用户可以在刷新页面后无限次地投票,并且正在记录结果。

我想让用户在他们的IP投票时只投票一次,在他们投票后,在页面刷新时只是为了向他们展示结果。

这是代码

HTML页面:

<html>
<head>
<script>
function getVote(int)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("poll").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","poll_vote.php?vote="+int,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="poll">
<h3>Do you like PHP and AJAX so far?</h3>
<form>
Yes:
<input type="radio" name="vote" value="0" onclick="getVote(this.value)">
<br>No:
<input type="radio" name="vote" value="1" onclick="getVote(this.value)">
</form>
</div>

</body>
</html> 

PHP文件:

<?php
$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0)
  {
  $yes = $yes + 1;
  }
if ($vote == 1)
  {
  $no = $no + 1;
  }

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
fclose($fp);
?>

<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table> 

我想让用户在他们的IP投票时只投票一次,在他们投票后,在页面刷新时只是为了向他们展示结果。

1 个答案:

答案 0 :(得分:0)

您可以像这样保存用户的IP地址:

$insertvote = $yes . "||" . $no . "||" . $_SERVER['REMOTE_ADDR'];

但是,如果没有数据库,随着文件变大,它必然会变得无法管理,您必须扫描文件才能检查IP是否已存在。您可以按会话限制投票,但是再次,这也不是完全可靠的证明(顺便说一下,也不限制IP投票)。

<?php
session_start();

if(isset($_SESSION['voted'])){
    die('You have already voted.');
}

$vote = $_REQUEST['vote'];

//get content of textfile
$filename = "poll_result.txt";
$content = file($filename);

//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];

if ($vote == 0){
    $yes = $yes + 1;
}
if ($vote == 1){
    $no = $no + 1;
}

//insert votes to txt file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
$write = fputs($fp,$insertvote);
fclose($fp);

if($write !== false){
    $_SESSION['voted'] = true;
}
?>
<h2>Result:</h2>
<table>
<tr>
<td>Yes:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($yes/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($yes/($no+$yes),2)); ?>%
</td>
</tr>
<tr>
<td>No:</td>
<td>
<img src="poll.gif"
width='<?php echo(100*round($no/($no+$yes),2)); ?>'
height='20'>
<?php echo(100*round($no/($no+$yes),2)); ?>%
</td>
</tr>
</table>