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.
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.
How to fix
- Ensure that there is no empty line or HTML comments before the call to session_start function
- 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
<?php //Start bufferng the output ob_start(); print("Some text"); //Since the output is now buffered, //the above statement will not cause any error session_start(); ?>
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.