3

I have a website that needs to perform a certain backend function once per user session. I therefore want to be able to determine whether any given page view is the first within a given session.

According to the PHP docs:

session_start() creates a session or resumes the current one based on a session identifier passed via a GET or POST request, or passed via a cookie.

So is there any way to know whether the session is being created or resumed?

Or is this a situation where I have to check the current session ID against a list I maintain on the server, to check if it's been registered before? If so, does this necessitate writing to a database, or is there a less cumbersome, in-memory way of doing this?

Yarin
  • 159,198
  • 144
  • 384
  • 498

3 Answers3

8
<?php
session_start();
if(empty($_SESSION['exists'])){
    //handle completely new session here
}
$_SESSION['exists'] = true;
.... //continue on with normal request
Kenaniah
  • 5,103
  • 23
  • 27
  • You should use `!isset()` instead of `empty()`. If the key does not exist, PHP is going to throw a Notice error with `empty()`. – animuson Jan 18 '12 at 01:29
  • Animuson - PHP doesn't throw notices for empties when the key doesn't exist in 5.3. Probably true of earlier versions as well. – Kenaniah Jan 18 '12 at 01:31
5

All documented ways of checking for session "newness" have failed me in the past, so I tend to do

$_SESSION['existing']=true;

when starting a session, and then just testing

if (isset($_SESSION['existing'])) ...
Eugen Rieck
  • 62,299
  • 10
  • 67
  • 91
3

Check if $_COOKIE['PHPSESSID'] is defined (or whatever the cookie name is if you changed it from default.

If the cookie doesn't exist, then the session has just been created.

Niet the Dark Absol
  • 311,322
  • 76
  • 447
  • 566