【发布时间】:2015-04-30 00:05:41
【问题描述】:
我想设置一个 cookie,让用户在 4 个类别(悲伤、愤怒、有趣、酷)中只投票一次。 我是初学者,所以我知道我的代码非常不方便,但这是我的第一次尝试,所以我或多或少有几行代码对我来说并不重要。 由于某种原因,浏览器不会加载 vote.php 文件(当用户单击一个投票选项时调用)。我只是找不到错误...也许有人立即看到它? [在我插入cookie之前,代码文件加载完美,所以调用不是问题。]
<?php
require_once('connect.php');
$newsid = $_POST['id'];
if (isset($_POST['submit'])) {
if(isset($_COOKIE['votecookie']) && $_COOKIE['votecookie'] !== 'sad') {
if($_COOKIE['votecookie'] == 'cool') {
$query = mysql_query('UPDATE `index` SET cool=cool-1 WHERE id = {$newsid}');
}
if($_COOKIE['votecookie'] == 'funny') {
$query = mysql_query('UPDATE `index` SET funny=funny-1 WHERE id = {$newsid}');
}
if($_COOKIE['votecookie'] == 'sad') {
$query = mysql_query('UPDATE `index` SET enraging=enraging-1 WHERE id = {$newsid}');
}
setcookie('votecookie', 'sad');
$query = mysql_query('UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'');
$hosts = $_SERVER['HTTP_HOST'];
$uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extras = 'news.php?id={$newsid}&sad=1';
header('Location: http://$hosts$uris/$extras');
exit;
}
if(!isset($_COOKIE['votecookie']) {
setcookie('votecookie', 'sad');
$query = mysql_query('UPDATE `index` SET sad=sad+1 WHERE id = '{$newsid}'');
$hosts = $_SERVER['HTTP_HOST'];
$uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extras = 'news.php?id={$newsid}&sad=1';
header('Location: http://$hosts$uris/$extras');
exit;
}
if(isset($_COOKIE['votecookie']) && $_COOKIE['votecookie'] == 'sad') {
$hosts= $_SERVER['HTTP_HOST'];
$uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extras = 'news.php?id={$newsid}&sad=0';
header('Location: http://$hosts$uris/$extras');
exit;
}
}
else {
$hosts= $_SERVER['HTTP_HOST'];
$uris = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extras = 'news.php?id={$newsid}&sad=0';
header('Location: http://$hosts$uris/$extras');
exit;
?>
【问题讨论】:
-
您应该改用会话。用户可以修改和删除cookies
-
当你在一个只在
votecookie是notsad时运行的块内时,为什么你有if($_COOKIE['votecookie'] == 'sad')? -
关于header('Location: http://$hosts$uris/$extras'); - 因为这些是单引号,所以正在使用文字值 - 它试图重定向到 http://$hosts$uris/$extras。使用双引号解析字符串中的变量。 php.net/manual/en/language.types.string.php
-
您是否期望第一个
if块中的setcookie('votecookie', 'sad')更新在下一个if中测试的$_COOKIE['votecookie']?$_COOKIE仅在您刷新页面时设置。 -
感谢您的回答。 @Barmar:悲伤的事情确实是一个错误,我纠正了它。对于你的第二个问题:不,我不期望它