PHP Session for counting visits and redirect if (session['visits']=1)
21,307
Solution 1
Use isset()
to check if the key has been created:
<?php
session_start();
if (!isset($_SESSION['views'])) {
$_SESSION['views'] = 0;
}
$_SESSION['views'] = $_SESSION['views']+1;
if ($_SESSION['views'] == 1) {
header("location:index.php");
}
?>
Also be careful: you had if ($SESSION['views'] = 1)
which is sets the key to 1 not compares it, and the correct superglobal name is $_SESSION
not $SESSION
.
Solution 2
first of all (where @nivrig and @Yan dont fix)
if($_SESSION['views'] = 1){
header("location:index.php");
}
should be
if ($_SESSION['views'] == 1){
header("location:index.php");
}
and go with @nivrig his example is right
Comments
-
Leo almost 2 years
I am trying to make a page on which if you user comes first time it redirects to the index page but if user comes 2nd time the page doesn't redirect. I am using simple php session for counting the visit and an if statement for checking condition:
<?php session_start(); $_SESSION['views'] = $SESSION['views']+1; if($SESSION['views'] = 1){ header("location:index.php"); } ?>
The problem is to initialize the array with zero i.e
<?php $_SESSION['views']=0; ?>
It's niether as much simple as it seems and nor much tough.