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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With