简体   繁体   中英

How to avoid the catch-22 of PHP session_start() vs “headers already sent” warning?

I have an application that works TOTALLY fine on my local server.

It requires two things:

  1. An active $_SESSION so that a number of key data elements are available on every page. (Stuff like user_id, and user_role.)
  2. A couple of "require_once()" calls at the top of my pages, so that I have some constants available and standard messages available and the same header on every page.

Again, on my local server (using php 5.6), this is all fine and dandy.

On my HOST server (also using php 5.6), however, I have a catch-22:

  • If I call "session_start()" on each of my pages, I get a "headers already sent" warning, due to my use of "require_once()".
  • If I do NOT call "session_start()" on each of my pages, the $_SESSION variable is empty when it gets to the next page.

The only ideas I have seem very bad:

  1. Don't use sessions and pass all my data in the URL. This seems insecure, clumsy, and like bad practice.
  2. Don't use "require_once()", which seems really stupid as I'll have duplicate code all over the place.

Any ideas about what I should do? I am on a shared server, so I don't think I can modify the php.ini file. And my host company, who has been very helpful about any other issue, has been totally silent over the past 2 weeks as I've sent them questions about this.

I have created a very simple example that shows the issue. Probably the most informative bit is in the comments for "firstpage.php", specifically the "if" statement under the comment "Under what circumstances is session being started".

Here is the index page (called mytestindex.php).

 <?php // Make sure $_SESSION array is available. session_start(); //*************************************************** // Print to the screen information about the session // This sends headers on the host server. //*************************************************** require_once("printsessioninfo.php"); // Set SESSION variable for later use on other pages $_SESSION['emp_id'] = 100; echo "\\n\\nThe employee id stored in SESSION is: " . $_SESSION["emp_id"] . "\\n\\n"; // Open next page when button clicked. if ($_SERVER["REQUEST_METHOD"] == "POST") { // Set the name of the page we are going to next $filename = "firstpage.php"; // *************************************************************************************************** // If headers have't been sent (seems to depend on php.ini settings), simply call the header function // This is the code that has worked on my local machine for years. // *************************************************************************************************** if (!headers_sent()) { $redirect_to = "Location:" . $filename; exit(header($redirect_to)); // ******************************************************************************************************************* // If headers have already been sent (require_once() above will do that), using the header function // will generate a "headers have already been sent" warning on the host server. So need to use Javascript to avoid that. // ******************************************************************************************************************** } else { echo " Opening page with Javascript. "; $code = '<script type="text/javascript">'; $code = $code . 'window.location.href="' . $filename . '";'; $code = $code . '</script>'; $code = $code . '<noscript>'; $code = $code . '<meta http-equiv="refresh" content="0;url=' . $filename . '" />'; $code = $code . '<noscript>'; echo $code; exit; } } ?> <div> <form action="mytestindex.php" method="post"> <button type="submit">Go to first page</button> </form> </div> 

Here is the page it links to (called firstpage.php):

 <?php /* First page */ //*************************************************** // Print to the screen information about the session // This sends headers on the host server. //*************************************************** require_once("printsessioninfo.php"); //*********************************************************************** // Print out other information before session started again on this page if (headers_sent()) { echo "Headers have already been sent.\\n"; } else { echo "No headers have been sent.\\n"; } if (isset($_SESSION)) { echo "Session variable exists.\\n"; } else { echo "Session variable does not exist.\\n"; } //***************************************************** // Under what circumstances is session being started // and does it cause a "headers already sent" warning? //***************************************************** // THIS check is what works on my local machine, with no warnings about headers being sent. if ( (!isset($_SESSION)) && (!headers_sent()) ) { echo " START SESSION: session var is not set AND headers have not been sent."; session_start(); } elseif (session_status == PHP_SESSION_NONE) { echo " START SESSION: session does not exist"; session_start(); // THIS check is what works on my host server, BUT throws the warning about headers being sent. } elseif (!isset($_SESSION)) { echo " START SESSION: session var is not set"; session_start(); } else { echo " No need to start a new session"; } //****************************************************************************** echo "\\n\\n The employee id stored in the session variable is: " . $_SESSION["emp_id"] . " ."; if (session_status() == PHP_SESSION_ACTIVE) { echo "\\n\\n\\n NOW Session is active!"; } ?> 

Here is a snippet of code that prints out some session info, so I have demonstrate how "require_once()" affects things (called printsessioninfo.php):

 <?php // Print session info echo "<pre>"; $sessionfile = ini_get('session.save_path') . '/' . 'sess_'.session_id(); echo 'session file: ' . $sessionfile . ' '; echo 'size: ' . filesize($sessionfile) . "\\n\\n\\n"; if (session_status() == PHP_SESSION_NONE) { echo "Session does not exist!\\n"; } elseif (session_status() == PHP_SESSION_DISABLED) { echo "Session is disabled!\\n"; } elseif (session_status() == PHP_SESSION_ACTIVE) { echo "Session is active."; } ?> 

I was able to fix this (thank you "mister martin"), by moving the code for "session_start()" into my config.php file, making sure it was the VERY FIRST bit of code.

Then for every page in the application I made sure this was the first line of code:

<?php
require_once("config.php");

And that did the trick, for both development and host servers.

if (session_status() == PHP_SESSION_NONE) {
  session_start();
}

Explanation required as it seems it wasn't clear enough (??):

If the status of the session is NONE then start it.

http://php.net/manual/en/function.session-status.php

http://php.net/manual/en/session.constants.php

Also this should be called BEFORE any require or require_once

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM