Skip to main content

Common PHP session errors

Below are some of the common problems faced by beginners while using sessions in PHP.

Headers already sent

This is the most commonly faced error is also the easiest to fix. Lets first see what a typical HTTP response looks like.

HTTP Headers

As can see from the image headers always precede (come before) the content. The “headers already sent” error occurs when you call session_start after you have already sent some content to the browser. Event an empty line at the start of the file is considered as content and will cause error.

headers sent error in PHP

How to fix “headers already sent” error

  1. Ensure that there is no empty line or HTML comments before the call to session_start function
  2. Add ob_start at the start of the file. A call to ob_start causes the output of the server to be buffered, that is stored in memory. While output buffering is active no output,except the headers, is sent from the script. The output is stored in the buffer and sent to the browser at the end of the script. You can also send the buffer’s contents to the browser by calling ob_flush or ob_end_flush

Calling session_start multiple times

It is possible that session_start might get called multiple times by way of include files. This will not break you script but it might, depending on your error reporting settings, display a notice on your browser.

Multiple calls to session_start will result in an error of level E_NOTICE. Only the first call to session_start will be effective and all subsequent calls will be ignored.

One thought on “Common PHP session errors

  1. Very useful. I had so many includes in my script. I had to go through each file to find those blank lines, that plus adding ob_start() proved to be very useful. Thanks 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *

*