0

I have a page on my website that calls a php file using ajax. I require the user to be logged in to access either page, and use session_start() on the page that calls the php file (let's say main.php calls bg.php). I include a session_start() on bg.php as well, because I need to access the session variables. However, I am spammed with php notices that say

A session had already been started - ignoring session_start()

So, I tried using

if (!isset($_SESSION)) session_start();

However, I kept getting the error, so I tried removing it entirely, because it said it was being ignored anyways. However, then bg.php stopped recognizing session variables. How can I stop getting the notices?

kzhao14
  • 2,190
  • 10
  • 19

3 Answers3

1

You should check the session status with session_status() function to avoid repeated session start. For example:

if (session_status() == PHP_SESSION_NONE) {
    session_start();
}
Maksym Fedorov
  • 6,275
  • 2
  • 7
  • 29
0

I recommend to write a library file, that is included at very first place in all .php files. It contains functions and startup code, that is nneded by all/many other pages. This helps to create clear structures and avoid copy and paste common code parts.

*.php

<?PHP
require_once("lib-standard.php");
# .... more code

lib-standard.php

<?PHP
session_start();
# more startup code (locale, timezone, login, check users, check rights, ...)
# common functions
# common classes
Wiimm
  • 2,253
  • 1
  • 11
  • 20
0

I like to address php session control like this: after verifying the user, I'll set a session variable. like:

   $permitted_chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

   $_SESSION['loggedIn']=generate_string($permitted_chars, 20);

then on the top of every page I want my session control to be:

        <?php
        session_start();
         if (empty($_SESSION['loggedIn'])){
          header("Location: login.php");
          exit();
         }   

edit: Also, if you are loading external pages, like a dbconnect.php page, you would put just the:

        <?php
        if (empty($_SESSION['loggedIn'])){
         header("Location: login.php");
        exit();
       } 

at the top in those files....

if I really go robust, then I store the "logged in" generated code in a db table at login, load a couple of identifiers (like user and password) into the session variables, Then after my initial check, I would check if the session is valid like

     " select count users from user_tbl where `name`=`".$_SESSION['name']."` and `pass`=`".$_SESSION['pass']."` and `key`=`".$_SESSION['loggedIn']."`"

then

       if ($count=="0"){
        header("Location: login.php");
      exit(); 
       }
drtechno
  • 268
  • 2
  • 9