session_start must be the first thing in your document.
But sometimes it’s hard to keep it as the first thing always.
So, we have some alternatives.
- You can change output buffering with php ini file, but any shared host doesn’t give that feature for their client.
php_value output_buffering 1 to your
.htaccess file in the root directory.
- You can use php output beffering with php functions (not recommended)
This problem occurs because the server sends output to the browser as soon as php echos the first output. All the server-side-headers are sent along with the first output. So, you can’t send header infomation after that. It means that you can’t use session_start after sending an output to the browser. Anyway, above tricks will solve your problem.
Output buffering is a technique to keep the response not sent until the whole process is finished. After finishing all the server-side process apache or whatever server you using will send the output. There is a saying that output_buffering can slow down the process. In that case, my answer is yes. It can slow down it, but not more than 100ms (100 milliseconds). Also it saves your time and you don’t need to keep session_start always at the top
If you are thinking to be a backend-dev in the future , i would like to suggest you to learn OOP (Object Oriented Programming). It’s easy to handle sessions with a single class and only thing you need to do is defining an autoload function.