问题
I'm encountering a very new and strange issue.
Usually session_start();
is initiated at the top of every page but in my case it's only serving the purpose when it is placed below a included database connection file, something like,
<?php
include 'connection.php';
session_start();
?>
session_start();
doesn't work when it is put reversely like,
<?php
session_start();
include 'connection.php';
?>
Basically the values were initiated and stored in session variables in another file and these should be printed on the page where I'm encountering this strange problem.
What could be the possible reason behind such strange behavior of this function?
回答1:
If the included file is a session handler, session should be started below the session handler. In the following code connection.php
is handling session and creating connection to the database. Therefore, the following code shall initiate the session correctly.
<?php
include 'connection.php'; ///// is a session handler
session_start(); ///// shall serve the purpose.
?>
on the other hand session won't be initiated when the codes are put in reverse order like,
<?php
session_start(); ///// shan't serve the purpose.
include 'connection.php'; ///// is a session handler
?>
来源:https://stackoverflow.com/questions/23615239/php-session-start-isnt-working-when-is-initiated-at-the-top-of-page