PHP:防止标头和session_start

I've built my own educational MVC framework to learn more about PHP OOP, which I certainly have, but for the moment I have gotten myself into a pickle. I need to use sessions throughout most of the project, but also need to stream a file to the user at a certain page.

As I call session_start() by default before getting into my controller, I get the infamous Headers already sent thrown in my face when I need to stream a file from inside the controller to the user. Pretty logical.

As I make the session modification inside the controllers, I need the session_start() to be called in beforehand, but at that time, the controller obviously isn't loaded and there's no way my framework could tell whether It should call the session_start() or not. Creating a file with a white list of controller names that doesn't need sessions seems quite primitive.

What would be an appropriate way to get rid of sessions when I need to stream a file?

Starting the session belongs in the bootstrap, not in an object IMO.

I would tend to always start in one of the first lines of the bootstrap, regardless whether it will be needed in the current script or not. Performance implications are likely to be non-existent or minimal.

When you send any output means you are sending the header as well if one of the your file contain any white space after the enclosing tag header will be sent to server . Check your files if they does this thing

session_start must be called before any header sent to server. There should not be any space in the files which are included in between double check your files if they contain any space at starting or the end

Use OOP. Your controllers must somehow extend a base AbstractController. So, add a virtual method "NeedsSession()" that returns true by default. Now, override this method for the controllers that don't need a session. It's cleaner this way.

If all of your requests are leading to index.php file, that's where you should start your session (Headers already sent problem should disappear). Remember about UTF-8 encoding in your file (without BOM)