使用ob_start和ob_end_flush将CSS包含在全局文件中


Use ob_start and ob_end_flush to include CSS in a global file

我的站点上的每个文件都包含一个globals.php文件。我想在这个文件中加入一个CSS文件globals.css

问题是,如果我在globals.php中添加CSS,然后将其包含在所有文件中,我会收到一些错误,比如:

Warning: session_start() [function.session-start]:
Cannot send session cache limiter - headers already sent (output started at /...)
in /... on line 4

或在使用时

header('Location: ....');

有没有比在globals.php的顶部使用ob_start和在同一文件的底部使用ob_end_flush更好、更合适的解决方案,或者这种方法是正确的操作方式?

globals.php

<?php
ob_start();
//some costants and functions
?>
<head>
    <link href="/css/globals.css" rel="stylesheet" type="text/css">
</head>
<?php
    ob_end_flush();
?>

您在全局脚本的末尾刷新缓冲区,关闭缓冲区,所以如果您有类似的东西

header('...'); // this will work, no output yet
include('globals.php'); // flushes buffers, stops buffering, starts output
header('...'); // fails with "headers already send"

如果在包含globals文件之后执行任何header()调用,那么globals应该NOT刷新缓冲区。

如果您正在使用会话,请确保在执行其他操作之前调用session_start。错误消息表示您在完成一些输出或其他操作后试图调用session_start