开发者

PHP session question

If I have sessi开发者_StackOverflow中文版on_start(); at the top of my header page is it alright to include $page_title before the header page?

$page_title = 'Some Title';
include ('../includes/header.php');


Yes. As long as you don't output anything before it, you should be ok...

The reason is that session_start sends a few HTTP headers. So if you've already outputted anything (including errors), it will fail, and as such won't start.

The way around that, is to setup output buffering at the top of the file. Just make ob_start(); appear at the top of the page. That way, no matter what happens (within reason), you should be ok (as in any output will be "captured" by the buffer, and hence not interfere with the session comamnd)...

Edit: As requested, an example:

<?php
echo 'foo';
include '../includes/header.php';

Won't work since you've outputted something...

<?php
include 'non/existant/file.php';
include '../includes/header.php';

Won't work since the first include statement will emit a warning because it couldn't find the file...

FooBar<?php
include '../includes/header.php';

Won't work since you're outputting something before hand (the text before the <?php line)...

<?php
ob_start();
echo 'foo';
include '../includes/header.php';

WILL work, since the output is captured by the buffer...

FooBar<?php
ob_start();
include '../includes/header.php';

Will not work, since the output buffer is started after the output is started...

<?php
include 'some/valid/file.php';
include '../includes/header.php';

May or may not work. It depends if the first included file outputs anything. If it does, then it won't work (So toss a ob_start() before hand to try to ensure it works)...

Oh, and you'll likely want to change the include to require since you don't want to continue if it doesn't find the file...


session_start(); needs to appear before there's any actual output to the browser. Usually people put it above anything else simply to avoid confusion etc. but in this particular case you'll be ok as a variable assignation is not output.


Yes.

You cannot output anything to the browser before starting the session.

E.g. You cannot do this

echo "This will break";
session_start();

This is because the session is set in the page header, and by using echo/print or similar you are forcing output before the page header is sent, thus breaking the ability for the session to be correctly started.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜