简体   繁体   中英

How to display correct output of Sessions & Cookies in PHP

I have a problem with this program of Sessions & Cookies.

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. 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:

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.

You should print the session var

echo "<h1>No. of visits=" . $_SESSION['nv'] . "</h1>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM