说明:本例通过获取客户端IP地址来限制用户的投票次数,每个IP只可以投票一次。
实现:获取客户端IP地址需要使用$_SERVER[ ]全局数组中的$_SERVER['REMOTE_ADDR']参数。本例将客户端IP地址存放到数据库,当用户提交投票时,判断该IP是否在数据库中,从而实现通过客户端IP限制投票次数。
(1)创建数据库:
数据库名字db_test ,表名为 tb_iplimit;
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `tb_iplimit`
-- ----------------------------
DROP TABLE IF EXISTS `tb_iplimit`;
CREATE TABLE `tb_iplimit` (
`ip` varchar(16) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
(2)IPLimit.php 源码:
<?php
$conn = mysql_connect("localhost","root","root"); //hostname,username,userpassword
mysql_select_db("db_test",$conn); //databasename,connection name
mysql_query("set names utf8"); //set charset
$ip = $_SERVER['REMOTE_ADDR']; //get client ip
$insert = "insert into tb_iplimit(ip)values('$ip')";
$select = "select * from tb_iplimit where ip = '$ip' ";
if(isset($_POST['submit']) and $_POST['submit']=="vote"){
$value = mysql_query($select,$conn);
//echo "value: ".$value;
if(mysql_num_rows($value)==0){
$result = mysql_query($insert,$conn);
//echo "<br/>result: ".$result;
if($result){
echo "<script>
alert('vote success!');
window.location.href = 'vote.html';
</script>";
}else{
echo "<script>
alert('vote failed!');
window.location.href = 'vote.html';
</script>";
}
}else{
echo "<script>
alert('You have voted!');
window.location.href = 'vote.html';
</script>";
}
}
?>
(3)vote.html 源码:
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>vote</title>
</head>
<body>
<form action="IPLimit.php" method="post">
1.Do you like this game?<br />
A.<input type="radio" name="question1" value="like" /> Yes, I like it.<br />
B.<input type="radio" name="question1" value="dislike" /> No, I hate it.<br />
<input type="submit" name="submit" value="vote" />
</form>
</body>
</html>