简体   繁体   中英

don't I need to use session_start() to use session global variables?

A novice php learner. I read in a book, and continue to see this at certain forums and tutorials that the statement: session_start() is required to access all global session variables. And yet, multiple solutions offered at stackoverflow suggest using a block of this sort:

if(!(_isset($_SESSION['user']))){
   session_start()
}

to be able to access the session variables. Based on my understanding, the session variable $_SESSION['user'] could only have been set at a previous php file by starting a session, and is "only" visible to the current page after the session_start() statement is called. Yet it produces the notice:

Notice: A session had already been started - ignoring session_start().

what am i missing?

Thanks everybody!

Your first block of code should be checking if the session variable is set, rather than the user variable exists in the session:

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

However, if you just ensure that you only have a single session_start() per page then you can avoid the "A session had already been started" notice.

session_start() is required to read / set any session variables.

Generally, I would think your code should look like this:

session_start()
if(!(_isset($_SESSION['user']))){
   // do stuff here
}

However, the error message implies that you have already started the session elsewhere in your file.

You might have auto_start turned on somewhere (php.ini, .htaccess, etc)? http://www.php.net/manual/en/session.configuration.php#ini.session.auto-start

Here is a scenario where your error would be triggered :

index.php:

 <?php session_start(); 
    require_once('some-page.php'); ?>

some-page.php:

<?php session_start(); // this would make an error when included to index.nl ?>

some-page.php should not have session-start in it as index.php already has started the session.

Also note that going to another page or even closing the tab will not reset your session variables ! so if you set S_SESSION['user'] = 'someuser'; , you close the tab and go to the website again, the session is still there and $_SESSION['user'] would still have someuser as value ! to manualy destroy the session , use session_destroy();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM