set cookie add 1 to cookie name everytime user clicks button

时间:2018-09-01 22:53:33

标签: php html cookies

So I'm currently making a site that includes purchases. Instead of signing up I want to set a cookie then every time a user clicks the buy button, it'll add 1 to the cookie name. Then when the cookie name = $_POST['user'] + 10 I want to echo 'too many right now' or something along those lines. I can't get this to work and have tried multiple times. There is no error in my html or anywhere else in my html. I just can't get this to work. Here is my code:

<?php  
$cookie_name = $_POST['user'];
setcookie($cookie_name,  time() + (86400 * 30), "/");

if(!isset($_COOKIE[$cookie_name])) {
print 'Cookie with name "' . $cookie_name . '" does not exist...';
} else {
print'Cookie with name "'. $cookie_name .'"value is:'.$_COOKIE[$cookie_name];
}
if(isset($_POST['button'])) {
setcookie($cookie_name, '+1', $cookie_value);

}

if (setcookie($cookie_name == $_POST['user'], +10)) {
echo 'to many right now';
}
?>

I obviously have a html form with the attributes name = 'button' and name = 'user' I just want to know how I can achieve what I said I was trying to do above. Any help is appreciated, thanks.

1 个答案:

答案 0 :(得分:0)

您显然已经超出了深度,并希望setcookie将以某种方式为您完成所有工作,阅读,调整和测试Cookie。作为the manual makes clear,它只做一件事:

  

setcookie()定义要与其余HTTP标头一起发送的cookie。

它有两个主要参数:一个字符串,它是要发送到浏览器的cookie的名称;一个字符串,它是要发送的值;其他参数都是可选的,并更改何时何地可见;现在暂时忽略它们。请注意,第二个参数不是方程式,也不是要进行的调整,它只是要存储的文本字符串。

和以往一样,关键是分解问题;完成以下每个步骤,并确保其正常工作,然后再进行下一步:

  1. 确定cookie的名称(不会更改的部分,因为稍后您会再次找到它)。
  2. 测试是否已在上一个请求中设置了cookie。
  3. 如果有,请将其值放入新变量中。
  4. 将该值增加1
  5. 如果没有现有的cookie,请将变量设置为初始值,例如0或1
  6. 使用setcookie
  7. 将具有新值的cookie发送到浏览器
  8. 测试该值是否已达到某个阈值,并回显一条消息。

请注意,在上文中,只有一个呼叫setcookie;您的大多数逻辑只是处理数字,而根本不需要了解Cookie。