When and why use session_start?

Asked

Viewed 10,069 times

9

Certain that, in short, session_start() "starts a new session or summarizes an existing session", but some questions:

The function should only be called once, after the login user’s?

Why to start a in performing login?

What relation to the global variable $_SESSION?

Its use concerns the security of information?

Which would be to say, "summarize an existing session"?

What its use and non-use causes in a user authentication system?

If possible, I would like an example MVCE

  • Where Voce needs the $_SESSION you must use the start_session() before, in order to use

  • 1

    I know that sessions are saved in files. I imagine before giving a start_session, session is not loaded. Unable to use it $_SESSION.

  • I believe all your doubts are resolved by the answers to the question I have indicated ;)

  • The question is good, it does not deserve negative, but I believe it is broad. It could be divided into other questions, in my opinion.

2 answers

23


A session is what identifies the user. The function of the session_start uses a file located in the temporary folder, (/tmp/) by the name of sess_*. The * is the same value as cookie (PHPSESSID) sent by the user or the parameter contained in the url, the method of sending sessions per parameter is not recommended

Just to complement, the sessions may NOT BE AVAILABLE, as long as you use the session_set_save_handler or create another session method, including to connect directly to the database, see in this example, but logically the default is file storage and therefore not the case, besides there are other types of session uses, which do not use the standard PHP method


The function should only be called once, after user login?

Yes. When using the session_start() such a function checks if there is a session_start() previous and if there is it prevents it from existing and so can only be called once per "page".


Why to log in when logging in?

This is done to recognize the user, without the session it becomes impossible to identify who logged in when the user goes to another page. When using the session_start() is created (or used) cookie of PHPSESSID with a value that should be unique, this allows the user to navigate on multiple pages and always be recognized by the same cookie and therefore by the same session.

<?php
session_start();
// Ele aqui já vai enviar um cookie ao usuário, independente do que ocorrerá.
// Suponha que o cookie seja "ABC".

if($senhaCorreta === true){

   $_SESSION['id'] = 123;
   // Agora a sessão (o arquivo sess_ABC que está no /tmp/) possui um chave "ID" com "123".

}

The user at this time will own the cookie of "ABC" which will be sent in all requests made on the same domain. On the server side we have a file, name sess_ABC which contain the information of id equal to 123.


What relation to the global variable $_SESSION?

Toda. The array $_SESSIONwill only exist when the session_start() was previously called. The $_SESSION will be used to read and record session information, rather, the $_SESSION is used to read session file data.


Its use concerns the security of information?

That’s my favorite part! D

The sessions are safer than the cookie, but they’re not so far away.

This is a delicate case. The most obvious of all would be if someone had access to the session files. If you use encryption in the database and use the usurer’s password to decrypt and store it in the session an attacker could have access to session data in the temporary folder.

But, that’s just a problem. The biggest problem of all is that you use someone else’s session.

Facebook for example uses the session c_user, xs and presence to perform some actions.

curl
-H "cookie: c_user=?; xs=?; presence=?" 
-H "user-agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
"https://www.facebook.com/"

Would be the same:

document.cookie = "presence=?;";
document.cookie = "xs=?;";
document.cookie = "c_user=?;";

If the c_user, xs and the presence is compatible with an open session you will, without logging in, have access to the user’s account. This indicates that if you go into someone’s home, and quickly open the F12 console and see the HEADER of Request Headers and send the Cookie to your email, when you get home you can use the session that was opened, live reasonably close. I also made a posting of a Facebook issue and also mentioned the use of cookie.

So the sessions are not safe. One thing you can do is get more and more user data, for example, check if the browser is the same, if the IP is the same, if the connection location is the same, even try to see if the screen resolution of the user is the same.

For example:

if($_SESSION['seguranca']['ip'] !== $_SERVER['REMOTE_ADDR']){
   session_destroy();
}

Whenever the user changes the IP it will be necessary to redo login, few websites do so. Another option is to have a timeout low, ie quickly the session will expire, banks and similar services is common that.

However this is an inconvenience, if someone is with a 3G IT (you know how it is right?!) and the connection falls and comes back will have another IP and therefore... is, another login.

But that’s just the problem? nop, we still have a few:

  1. Generate sessions alopradamente, in search of an already open
  2. Predict the next session that will start, based on what you got.
  3. Self-xss, user injects a JS and sends sessions to "someone"
  4. Man-in-the-Middle, packet interception

The session is a set of number and letters, you can try to generate to access a person’s account and there is a more complex problem that would be predictability.

Suppose you use the following cookie:

PHPSESSID = session01

What would be next? Yes, the possibility of being session02 is almost 100%, so just wait a few minutes, depending on the traffic of the website, to access the session of others.

This can also occur when using sessions with low randomness. Actually generating something random is extremely difficult, but some are worse than others.

The /dev/random tends to be more predictable than the /dev/urandom on some platforms, for example, in addition to session.hash_bits_per_character which defines a greater or lesser variation of characters, if you like see this and that. ;)

The operating system collects entropia (I don’t know if it’s the right term!) often, this is collected based on the use of hardware. For example, on a personal computer, the movement of the mouse, the use of Hds, the typing of the keyboard, packets sent and received on the internet (...) this information is the basis for randomness, that is to say you (or your software on the server) is only random thing in this world. This randomness also includes the name of the sessions. However, this is scarce and each algorithm will try to do something when there is no more entropy needed, or simply ignore generating predictable data, see here.

Sessions are not invulnerable, they also have (or may have) a lot of problems and you will have to do something to try to minimize that, but they are safer than keeping it all in one cookie.

To prevent "Self-xss", when the user unknowingly injects malicious code using most of the time the F12 CONSOLE. In common situation the JS has access to all cookies on the page, this allows the code to obtain the cookie of the session and then send it to the external server, controlled by the "invader". To protect against this you must use the session.cookie_httponly=1, this will prevent the sending of session cookies to another server and also use the session.cookie_secure=1. As additional also use the session.use_only_cookies=1, otherwise someone may have the session in the URL parameter, so when you send the link to someone they will have access to the session.

One of the things that can prevent (or hinder) packet interception is only to transmit the data on TLS/HTTPS and use the session.use_only_cookies=1 as an additional to prevent you from only getting the session at the URL. Also use subdomains for static content (estatico.site.com, img.site.com...) and thus cookies will only be sent to the site.com but will not be used for subdomains. This will reduce the number of requests that have session identification. Logico, as stated earlier, limiting by IP among other factors will make it difficult for someone to use the session, even if they capture it.


Which would be to say, "summarize an existing session"?

You mean if there is one cookie of PHPSESSID sent by the client PHP will use the session that was previously opened.

If you do:

curl 
-H "Cookie: PHPSESSID=ABC" 
meusite.com/perfil.php

The meusite will use the PHPSESSID of ABC, so basically you’re continuing an already open session.

What its use and non-use causes in a user authentication system?

If you do not use the standard PHP session system you will not be able to identify the user, except if you use another mechanism to have sessions, such as:

  1. Cookies
  2. Websockets

You can save everything on Cookies, of the kind Nome=Inkeliz, but this is totally unsafe than using standard PHP sessions, because the user has full control of the values that are saved. This is good if you have a website that does not have an authentication system, ONLY. But cookies can be improved, an alternative is to encrypt or sign a cookie, for example using JWT:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjEiLCJub21lIjoiSW5rZWxpeiJ9.Z3mq41cyKyQzO/aS+6zmHElygGabWCsa3U44Yfpu5RU=

This was generated using:

$headers = [
    "alg" => "HS256",
    "typ" => "JWT"
];


$payload = [
    "id" => '1',
    "nome" => 'Inkeliz'
];

$chave = 'sua_senha_legal';

$conteudo = base64_encode(json_encode($headers)) . '.' . base64_encode(json_encode($payload));

$assinatura = base64_encode(hash_hmac('SHA256', $conteudo, $chave, true));

$token = $conteudo . '.' . $assinatura;

This means that if the user changes the id for 2 the signature will not be equal, this is similar to the PGP signature, for comparison. The signature is generated based on the password sua_senha_legal and there are other types of signatures (and also encryption) that can be done to use as a session. This is a session method, even if you don’t use the default session system.

The use of Websockets is more complex. When the user logs in he will establish a persistent connection with the device and this connection is the ONLY thing that identifies the user, without use of cookies as identification. If the user gives F5 or goes to another page the connection will be interrupted and therefore have to login again. It theoretically is the most secure, because once the connection is created no other can be created with the same identification and if it falls the session ends.

If you do not use (or cannot use) any of the above solutions and even the common session method will be impossible to identify the user, one way or another you will need to use sessions.

  • Top man.... Then voi take a break for the links...

  • Have you considered answering this question? http://answall.com/q/39675/7210

  • 2

    I believe the information from .txt is mistaken. If I am not mistaken, these files are created without extension in the temporary folder. But it is certain that temporary files are created to record the data.

  • @Wallacemaxters I edited. It’s no extension anyway, I don’t know where I got the .txt.

  • 1

    @Jorgeb. I will reply when I have time, you can use the websocket for this, when you login create a id and send through the connection. The problem is that all user action, all requests, must be made by websocket, your site should be "all in one page" because the user cannot exit it.

  • @Inkeliz I’ve already followed another path with cookies, but I think it was interesting to know that way too.

  • @Inkeliz, when you say, "can only be called once per "page"." This means that on all other pages I intend to access user information, via Mysql, for example, I must call it?

  • @luccasrodrigo exact. You should call it on every page you intend to use the sessions. Without this you will not be able to read any information stored in the session. The session_start is like a mysqli_connect. If you don’t call the session_start cannot obtain session data in the same way as without mysqli_connect it will not be possible to retrieve data from the database. ;)

Show 3 more comments

-3

The function should only be called once, after user login?

In this context, the session has nothing to do with the user logging in or not.

A server session starts when a user enters the site. At this time, the server reserves a memory space, where it stores session status information, so that even if you exchange pages, session information is kept.

The session_start() function is used to give your code access to the $_SESSION session variable, so it only needs to be called once.

It’s like telling the server you want access to this user’s session.

Why to log in (/tags/session/info) when logging in?

When a user logs in, the session he starts occurs at the application level and is controlled by it. It has nothing to do with the server session, which was started when it entered the site.

However, the application will use the server session to save login information, thus the system remembers that the user has logged in.

What relation to the global variable $_SESSION?

$_SESSION is an array that stores session information. session_start() allows access to its contents.

Note that the session will exist anyway.

Its use concerns the security of information?

Each user starts a private session when entering the site. One user does not have access to the information of another. However, the app can have access to information from all sessions.

For example, the 'who’s online' feature that some apps have will use session variables to access information like Qtde. of users connected to the website, IP, etc.

Which would be to say, "summarize an existing session"?

A server session has a lifecycle. It starts when a new visitor enters the site and lasts for a while after he has left the site.

However, if it returns to the site, within the lifetime of the session, it restarts (resume).

What its use and non-use causes in a user authentication system?

Many systems use the session to control authentication. Otherwise, you would have to pass a variable from page to page and that would be very risky.

More information on http://php.net/manual/en/reserved.variables.server.php

  • I would like to understand this part :"A server session starts when a user enters the site. " This session you refer to is different from the one initialized with session_start() ?

  • The session is a server thing. When you joined this site, you signed in. It ALWAYS happens. Now, if php wants to access some of this information that is recorded in $_SESSION, it needs to call session_start(). session_start() not logging, but code access to session variables.

  • Here comes the doubt (note I am not testing it, I want to understand, because it is relevant to me, that point), if the sessions are recorded in a file and I have access to the folder tmp even without initializing the session with session_start() I’m gonna have a session_id() stored in that file ?

  • Feel free. We’re here to learn. If this were a test I wouldn’t have passed... I had no idea where this information is recorded. I never even thought about it. Besides, maybe a server configuration will change the session’s storage location. I don’t know. Inkeliz’s answer is super complete, but it can be confusing. If you’re using php, it’s much simpler, give a session_start() and have access to session information.

  • 2

    @Magichat already explained this here somewhere. When the session is started, a cookie is saved in the browser with the session_id. That one id is used to access a file in the folder /tmp of your server, which contains a code generated by the function serialize. PHP uses unserialize when you access the information of $_SESSION in order to obtain this file. There is a bridge between server and client (file and cookie) for this information to exist.

  • @Magichat if you are interested in how the function works, read my reply: How to keep the session after browser close?

  • What do you mean by " Is there a bridge between server and client (file and cookie) for this information to exist"? and " This id is used to access"to access or create the file ? @Wallacemaxters

  • @Magichat the "cookie" called "PHPSESSID" (which is created when you use Session_start), receives the value of session_id. So, the page’s content, PHP will know which file on the server it will take to retrieve the session data (The session receives the ID name and sends it to the cookie). See the other answer :p

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.