PHP cookie和访问计数器


PHP Cookies and Visit Counter

我正在努力学习php(全新的),我正在努力实现在这篇文章中发现的完全相同的事情,这篇文章使用cookie作为计数器和网站上的最后访问:

PHP cookie访问计数器不工作

但是不像那个帖子里的用户,我遇到了这个臭名昭著的错误:

"这是你第一次上服务器!"警告:无法修改报头信息-报头已经由(output started at in(…)在第17行

发送

第17行:setcookie('visitCount1');

现在我意识到这是常见的,搜索SO,发现这篇文章:

如何修复"标题已发送"PHP出错

我仔细阅读并检查了可能发生这种情况的原因,包括空白和在任何html代码之前输入我的浏览器提到的php行,并删除结束标记"?"我也试着把ob_start()在我的代码的开始,但仍然是相同的错误结果。

这是我试图运行的代码(取自上面的帖子):

<?php
$Month = 3600 + time();
date_default_timezone_set('EST');
setcookie('AboutVisit1', date("D M j G:i:s T Y"), $Month);
?>
 <?php
if(isset($_COOKIE['AboutVisit1']))
{
$last = $_COOKIE['AboutVisit1'];
echo "Welcome back! <br> You last visited on ". $last . "<br>";
}
if(isset($_COOKIE['visitCount1'])){
 $cookie = ++$_COOKIE['visitCount1'];
 echo ("You have viewed this page" . $cookie . "times.");
}
else
{
echo "It's your first time on the server!";
setcookie('visitCount1');
}
?>

我使用netbeans 8.1与wamp服务器和chrome浏览器。还有什么办法可以解决这个问题?

如果我只是在浏览器上或通过netbeans进行测试,实际上有可能看到cookie和会话跟踪记录吗?

我必须包括一个html标题和正文还是我可以把它放在php正文?

在php上它工作(有些),我得到这个(总是相同的时间):

欢迎回来!你最后一次访问是在2016年8月9日星期二15:43:00 EST这是你第一次上服务器!

您发布的代码包含一个空白。看:

setcookie('AboutVisit1', date("D M j G:i:s T Y"), $Month);
?>
 <?php

看到结束和开始之间的空格了吗?

问题是,在发送最后一个cookie之前,您正在回显消息:setcookie('visitCount1');在您已经运行echo "It's your first time on the server!";(或echo "Welcome back! <br> You last visited on ". $last . "<br>";)之后被发送到浏览器。请确保在发送最后一个cookie之前不要使用echo函数。

编辑:正如其他人指出的,在你的代码中也有一个空格。

考虑到你是新人,这里有一些建议

<?php
// if you are going to change the timezone, best to always make this first, so it effects everything in the script
date_default_timezone_set('EST');
// 3600 seconds = 1 hour not Month
// give your variables proper names it will help if you get into that habit from day one
$one_hour = 3600;
$expires = $one_hour + time();
// check if visit cookie exists and increment it, otherwise, this must be visit 1
$count = isset($_COOKIE['visitCount1']) ? ++$_COOKIE['visitCount1'] : 1;
// set cookies at the start, before outputting anything
// i would also recommend setting the path, as that can catch you out if you have a deep directory structure, / will mean the cookie works for the whole site
setcookie('AboutVisit1', date("D M j G:i:s T Y"), $expires, '/');
setcookie('visitCount1', $count, $expires, '/');
if(isset($_COOKIE['AboutVisit1']))
{
    $last_visit = $_COOKIE['AboutVisit1'];
    // you don't need to use . to concatenate variables if you use double "
    echo "Welcome back! <br> You last visited on $last_visit <br>";
}
if(isset($_COOKIE['visitCount1'])){
    // you dont' need () when you do echo
    // you don't need to use . to concatenate variables if you use double quotes "
    echo "You have viewed this page $count times.";
} else {
    echo "It's your first time on the server!";
}
// you don't need trailing ?>

应该在输出任何其他内容之前调用setcookie()函数。所以在你的代码中有一些部分在setcookie被调用之前输出了一些东西