Today I am going to explain simple but tricky interview question. Before Some days, one of my students asked me “why we need to add session_start() functions at the first line of code?” question and want to share my answer here
Web Server sends the response to the web client and browser renders the HTML information of the page.so Before the HTML information rendered into a screen and display content to the screen, all header information like cache the page set by header r not,require to execute at the beginning of the page because once something print or body tag is executed, no more headers can be sent.
And the setcookie() and session_start() functions add headers to the response. So we must have to add both functions before any output or any HTML rendering starts.
Warning: Cannot modify header information - headers already sent by....
Above error says that file contain print statement before you sends a header so If you find “headers already sent” error message, make sure that there are no print/echo statements before you call setcookie( ) or session_start( ) functions.
You may also like: