Please, explain how session_start()
function works.
I don’t understand the sequence of actions when starting a session in php. Try to explain.
HTTP is a client – server architecture. It means that the browser sends its request, the sever processes the request and sends back its answer. Each of these actions has appropriate headers.
I checked (with headers_list()
) what headers are sent back by the server with its answer when I want to start session. And among others there is header
Set-Cookie: PHPSESSID=7f4cbf53fbcd4717792447f32da7dba8
It seems that everything is ok, the server gives order to the browser to set the cookie.
But.To start session I have to include the session_start()
function in the beginning of the code of the page. So this function is started when the browser begins parsing the page. The browser meets the php opening tag <?php
followed by the session_start()
function. Immediately it delegates control to the server. And the server only now starts the function. Only when it has already sent the page to the browser with all the headers.
So I don’t understand how server can send Set-Cookie
header before the browser starts parsing the page and meets the session_start()
function? How it knows that it has to put Set-Cookie
header before the command session_start()
is executed? Or I misunderstand the process?