-->

php session and path setting

2019-08-27 17:03发布

问题:

I would like to separate my source folders into two: The folders that contain the code that you type into the address bar and those that make up parts of the page (tiles) and other code (classes, etc). So at the start of every php file I added:

<?php
// index.php
include("config.php");
include("session.php");
?>

Config contains just this so far, but allows me to expand if I need other directories (logs, etc.)

<?php
// config.php
$_PATHS["base"]      = dirname(dirname(__FILE__)) . "\\";
$_PATHS["includes"]  = $_PATHS["base"] . "includes\\";
ini_set("include_path", "$_PATHS[includes]");
?>

And session has amongst other things, in the constructor, a call to session_start. It also requires other classes which are included elsewhere - which necessitates the config being listed before the session inclusion. However I get the error

Warning: session_start() [function.session-start]: Cannot send session cookie - headers already sent by (output started ...

If I switch the includes around that particular error goes away but I need to start manually munging the links to the header files. Is there anyway of setting the directories first and still being able to use sessions or must session_start be the very first thing the a file includes?

回答1:

I don't know if you have already tried this, but as a means of testing remove the config.php include and paste the config code in there instead.

So this:

<?php
// index.php
include("config.php");
include("session.php");
?>

becomes this:

<?php
// config
$_PATHS["base"]      = dirname(dirname(__FILE__)) . "\\";
$_PATHS["includes"]  = $_PATHS["base"] . "includes\\";
ini_set("include_path", "$_PATHS[includes]");
//index
include("session.php");
?>

If it works then you have a problem with your config.php file* [see below], if it doesn't, does the error still point to the ini_set line? [assuming from your above comment that's where the current error points]

*I remember reading once [a while ago I admit] that a file being UTF-8 might screw up sessions. Trying to find a link

Ok I found someone who submitted a bug report concerning UTF-8 and session_start. Apparantly it isn't a bug - I didn't look into why - but either way it isn't quite the same issue. A type of UTF-8 encoding does cause session errors, just not the cookie error you are getting. See here if you are interested - UTF-8 Error



回答2:

The rest of that error is the exact bit that will tell you where the problem is! Chances are you have some trailing whitespace at the end of config.php.

(Either that, or session.php sends output before your call to session_start(), but I'm really just guessing now :)