0

In the login form of one of my PHP project. After all validation I set $_SESSION['username'] = $username (where $username value is coming from db_username of that user and when I write echo $username; it prints the correct value).

Suppose $username is "Admin" so $_SESSION['username'] = 'Admin'.

After successfully login, the page reloads automatically, and here the issue arise. As I'm already logged in, it must show My Profile menu instead of Login menu, but it shows Login menu. So I use echo $_SESSION['username'] which prints blank value, while it should print "Admin".

This works fine in my local server (XAMPP, PHP version: 7.0.9), but the problem occurs when I upload those code in live server (PHP version: 5.6.30).

PHP Session is running. As I use the following code to check:

if( !session_start() ) {
    session_start();
} else {
    echo 'Session is started';
}

Can anyone help me to fix this problem? Thanks in advance.

Taz
  • 3,718
  • 2
  • 37
  • 59
Shimul
  • 463
  • 2
  • 7
  • 33

2 Answers2

2

Assuming you are running PHP version greater thatn 5.4, use the session_status function like this:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

session_status returns following values based on the status of session.

PHP_SESSION_DISABLED if sessions are disabled.

PHP_SESSION_NONE if sessions are enabled, but none exists.

PHP_SESSION_ACTIVE if sessions are enabled, and one exists.

Community
  • 1
  • 1
Amit Joshi
  • 1,334
  • 1
  • 8
  • 10
0

This is the problem.

Replace this with

if( !session_start() ) {
    session_start();
} else {
    echo 'Session is started';
}`

This code

session_start();

There is no need to check if session is started. Php will display an error if you start session 2 times in a same page. So no need to check if it is started.

Rajendran Nadar
  • 4,962
  • 3
  • 30
  • 51