borna
borna

Reputation: 924

php session always created on refresh

I am new to PHP so have a very basic question I creating a page I am creating a page initially with user id and password, once user id and password are entered and submit is clicked, AJAX is called to validate that against database. once validation done I want to refresh the page which show more option to user I was thinking to use session but every time I refresh the page a new session is created I put this at the top of the page as a test and always when F5 is press I see "new session" on top of the page

<?php
if (!isset($_SESSION)){
    session_start();
    echo("new session");
}
else
{
    echo("old session");
}
?>

Upvotes: 2

Views: 1792

Answers (2)

baao
baao

Reputation: 73241

From php.net:

session_start — Start new or resume existing session

That means you have to start your session with

session_start();

on every page, in the first line, which will start or resume it. Check the php.net manual, it will help you understand how to handle and check sessions correctly.

Upvotes: 1

mcont
mcont

Reputation: 1922

session_start must be called always before anything related to a session. After calling it, you can get or set values of the $_SESSION variable.

Reference.

Your code should be:

<?php
session_start(); // always call this at top
if (!isset($_SESSION['has_been_here'])){
    $_SESSION['has_been_here'] = true;
    echo("new session");
}
else
{
    echo("already been here");
}
?>

Upvotes: 4

Related Questions