[英]How to display correct output of Sessions & Cookies in PHP
I have a problem with this program of Sessions & Cookies. 我的“会话和Cookie”程序有问题。
Plz see the following code:- 请查看以下代码:
<?php
session_start(); //session starts
if(! isset($_COOKIE['cnt']))
{
@$_SESSION['nv'] = 1;
}
else
{
@$_SESSION['nv'] += 1;
}
$val = $_SESSION['nv'];
echo $val;
setcookie("cnt", $val, time()+30 );
echo "<h1>No. of visits=".@$_COOKIE['cnt'] ."</h1>";
if (@$_COOKIE['cnt'] == 5)
{
setcookie("cnt", 0, time()-30);
session_destroy();
}
?>
It is not giving the correct output. 它没有给出正确的输出。
When I run the program for the first time, it shows: 当我第一次运行该程序时,它显示:
No. of visits=
Means nothing.. 没什么意思
& when I run the program for the second time, it shows: &当我第二次运行该程序时,它显示:
No. of visits=1
I want that my output should be displayed as "No. of visits=1" when I run the program for the first time. 我希望我的输出在我第一次运行该程序时显示为“访问次数= 1”。 But it shows this output at 2nd time. 但是它在第二次显示此输出。
Do help me please.. 请帮我..
The cookie set by setcookie
is sent along with the HTTP response the server sends to the client and, quoting the documentation: setcookie
设置的cookie与服务器发送给客户端的HTTP响应一起发送,并引用文档:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. 一旦设置了cookie, 就可以使用$ _COOKIE或$ HTTP_COOKIE_VARS数组在下一页加载时访问它们 。
You should print the session var 您应该打印会话变量
echo "<h1>No. of visits=" . $_SESSION['nv'] . "</h1>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.