What are sessions for PHP?

Question:

What are sessions for PHP?

Yes , with their help, you can make authentication less resource-intensive (supposedly without a database).

But , during authentication, we still have to make a request to the database, at least to make sure that the user is not banned.

Yes , sessions are used to transfer some global parameters.

But , for this there are methods like include and similar ones.

So why are sessions needed then?

Answer:

As an introduction, I want to ask you a counter, rhetorical question: why do you need LocalStorage in js if you have a Cookie?

Strange, but you did not mention cookies, although, in my opinion, sessions have the most in common with them (in fact, sessions are associated with cookies). And it’s completely incomprehensible what the include . This is a construct that includes the file code.

Sessions in PHP, by default, are stored on the server's file system. But it is customizable (and you can set the logic yourself, if you want, you can store it in the session database). The session will return a specific array for each request, with a specific session key. The session key is stored in a cookie, marked as session key (lifetime 0), and is usually updated after the browser is closed, i.e. the data is no longer available. But there are exceptions, for example, Google Chrome . For some reason, he keeps the key. Sessions, unlike cookies, are stored on the server (only the key on the client), the user does not have direct access, and more information can be written into the fields than in cookies.

About databases: yes, user verification is needed through the database, but there are a bunch of other places where sessions could be used. Narpimer – a basket in an online store.

Or let's imagine that you have a multi-step form with 900 fields, and you need to save the data, even if the user has left the page – sessions will help here.

Scroll to Top