PHP session_start(); isn't working when is initiated at the top of page

时光怂恿深爱的人放手 提交于 2019-12-13 05:04:55

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!