tags:

views:

156

answers:

5
<?php
session_start(); 
if(isset($_SESSION['views']))   {
    $_SESSION['views'] = $_SESSION['views']+ 1; }
else {
    $_SESSION['views'] = 1; }
echo "views = ". $_SESSION['views']; 
?>

I am trying to set the session and increment the session on every refresh. But its always returning "1" for $_SESSION['views']. What is wrong with this code?

A: 

Check your php.ini, check if cookies are enabled in your browser. I've tried your code and worked for me.

Vili
do i need to configure any thing in php.ini
praveenjayapal
Have you changed the session variables? If not, the default settings would be fine.Have a look at the cookies. Is there a PHPSESSID or something named like this?
Vili
A: 

It might be the browser cache, try Ctrl+F5. There's nothing wrong with your code

victor hugo
+1  A: 

Make sure you're not calling unset anywhere and make sure cookies are enabled.

I uploaded that snippet as-is:

Click here to test...

It works fine for me. Try it. Hit refresh a few times.

If it doesn't work for you it's your browser settings. If it works for you on my server but not on yours then there's a problem with your php installation.

McAden
A: 

try:

<?php
session_start(); 
if(isset($_SESSION['views']))   {
    $_SESSION['views']++;
else {
    $_SESSION['views'] = 1; }
echo "views = ". $_SESSION['views']; 
?>
  1. echo $_SESSION['views'] directly after session_start(); and examin the output.
  2. Make sure you're not destroying the session in this or any other scripts.
Babiker
A: 

As a tip for other folks with same problems: Had the same problem just now - and found out why, with the above test snippet. Watch out for any modrewrites! I had a bad modrewrite for my page, which caused the index.php to be loaded two times (one time for redirect, and once for the actual display) on every refresh. Try renaming your file to some awkward name and test it again.