Simon Skjerven
Simon Skjerven

Reputation: 1

PHP Sessions issue - Sessions won't initialize?

So, I'm using a simple login-script for a few pages, using sessions to identify the user, by putting the users name in a $_SESSION variable and then checking if the variable is set on each page. This worked fine when I ran the script locally through a WAMP-server - but when I uploaded it to a webhotel I ran into a weird issue.

The login-script, which sets the $_SESSION variable if the username and password matches up with information from a MySQL-database, somehow won't start the session. I have session_start(); at the top of every page, including the login-script, so I don't understand why it wont start.

Now, I found a script on here that is used to check for session-support:

     <?php
      // Start Session
      session_start();
      // Show banner
      echo '<b>Session Support Checker</b><hr />';
      // Check if the page has been reloaded
     if(!isset($_GET['reload']) OR $_GET['reload'] != 'true') {
         // Set the message
         $_SESSION['MESSAGE'] = 'Session support enabled!<br />';
        // Give user link to check
        echo '<a href="?reload=true">Click HERE</a> to check for PHP Session Support.<br />';
       } 
       else {
          // Check if the message has been carried on in the reload
           if(isset($_SESSION['MESSAGE'])) {
            echo $_SESSION['MESSAGE'];
           }
           else {
             echo 'Sorry, it appears session support is not enabled, or you PHP version is to old. <a href="?reload=false">Click HERE</a> to go back.<br />';
            }
       }
   ?>

The really weird thing is that this script tells me that session-support is enabled - and after running it, it suddenly works across all the pages. So I have to run this script (in its own file) every time I access the site, because the login-script won't set the $_SESSION variable without running this script first.

JUST TO MAKE SURE: I am NOT asking how to check if session-support is enabled or not; the issue is why sessions are not enabled untill AFTER I run the script above.

Why is this happening, and how do I fix it?

Upvotes: 0

Views: 387

Answers (1)

A J
A J

Reputation: 4024

Session is automatically started when session_start() function runs. To check if a session is set, you do not need that long code. Try this.

   if(session_start())
   {
     echo session_id();
   }

If session is started, session id will be printed. Else, it won't.

Upvotes: 1

Related Questions