【发布时间】:2017-11-28 12:13:40
【问题描述】:
当用户点击点击获取优惠!它显示了报价,但是当我单击相同的按钮或刷新页面时,我必须显示“您已经使用了报价”消息。我想根据 IP 将它存储在 cookie 中,我试过但它不起作用。我是 PHP 的初学者,非常感谢任何帮助。
HTML
<div class="btn">
<button class="button" onclick="showoffers()" >Click to avail offer!</button>
</div>
<div class="offer">
<div id="coupon"></div>
<div id="nooffers"></div>
</div>
JS
function showoffers(){
jQuery.ajax({
url: 'cookies.php',
type: 'POST',
async:false,
dataType: "json",
success: function(data) {
if(data.Status==1){
jQuery('#coupon').html('');
jQuery('#coupon').html(data.msg);
}else{
jQuery('#nooffers').html('');
jQuery('#nooffers').html(data.msg)
}
}
});return false;
}
PHP
cookies.php 文件
<?php
$rand_keys='';
$input = array('You got 40% off on all plans');
shuffle($input);
$rand_keys = array_rand($input, 1);
$now = time();
$your_date = strtotime("2017-11-25");
$datediff = $your_date - $now;
$day= floor($datediff / (60 * 60 * 24))+1;
$ip= $_SERVER['REMOTE_ADDR'];
if (isset($_COOKIE['offers_ip']) && $_COOKIE['offers_ip']!='') {
$vArray=array('Status'=>0,"msg"=>$_COOKIE['offers_ip']);
echo json_encode($vArray);
}
else{
$value = $input[$rand_keys];
setcookie('offers_ip', $value, time() + (60*60*24*$day), 'offerpage.php');
$vArray=array('Status'=>1,"msg"=>$input[$rand_keys]);
echo json_encode($vArray);
}
?>
【问题讨论】:
-
推荐格式化cookies.php文件的代码。
-
@TomAranda 谢谢,但我该如何重写?
-
我现在看起来不错。
-
您是否希望每个 ip 仅提供一次优惠?还是每个用户登录?
-
对于所有用户相同的优惠,所以你的意思是每个IP地址只能使用一次,?如果我有 2 台笔记本电脑,然后使用同一个用户登录,我应该可以使用它两次,因为我们将 IP 地址存储在您的 cookie 中而不是用户名中,笔记本电脑 1 和用户 1,笔记本电脑 2 和用户 1,对不起,我很困惑,因为我们是显示与用户相关的“您已使用此优惠”
标签: javascript php jquery ajax cookies