Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Session for counting visits and redirect if (session['visits']=1)

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.

like image 585
Leo Avatar asked Dec 05 '25 18:12

Leo


2 Answers

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.

like image 122
johngirvin Avatar answered Dec 08 '25 10:12

johngirvin


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

like image 44
ryanc1256 Avatar answered Dec 08 '25 12:12

ryanc1256



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!