stonecutter
stonecutter

Reputation: 77

add number in session not valid

index.php

<?php
session_start();
var_dump($_SESSION);
if (!isset($_SESSION['count'])) {
    $_SESSION['count'] = 0;
} else {
    $_SESSION['count'] += 1;
}

var_dump($_SESSION);
?>

What I want to do is store a number in the session, when I reload the page, print the session and add one to the number.

The problem: "add one" seems executed two times when one reload; one reload

array(1) { ["count"]=> int(3) } array(1) { ["count"]=> int(4) }
$ cat sess_xxxxx
count|i:5;

why the number store in the session become 5, the last var_dump in the page is 4?

The web Server I use is Nginx.

Upvotes: 0

Views: 61

Answers (2)

stonecutter
stonecutter

Reputation: 77

I had request the /index.php twice;

The request to http://mywebstie, default send two request "GET /" and "GET /favicon.ico", and My web server Nginx config:

location / { 
    try_files $uri $uri/ /index.php?$query_string;
}  

the "GET /favicon.ico" is redirect to /index.php。
So the page were reload twice, and the "add one" be executed twice.

Upvotes: 0

Vasim Shaikh
Vasim Shaikh

Reputation: 4532

<?php  

session_start(); 

if(isset($_SESSION['count'])) 
    $_SESSION['count'] = $_SESSION['count']+1; 
else
    $_SESSION['count']=1; 

echo "views = ".$_SESSION['count']; 

?> 

Explanation

session_start() : It is a first step which is used to start the session.

$_SESSION['count'] :This is the session variable which is used to store views count for a user’s session.

isset() : It is a standard php function which returns true or false depending upon whether the passed parameter is set or not.

Update :

<?php

print_r($_SESSION);

session_start();
if (isset($_SESSION['count'])) {
    $_SESSION['count'] = $_SESSION['count'] + 1;

} else {
    $_SESSION['count'] = 0;
}

?>

Upvotes: 1

Related Questions