How to check if a session ($ _SESSION) exists or is active in PHP?

0

Is there a native function of PHP that you can use to check if a session for a particular user is open?

For example, I have a $_SESSION['usuario'] = "400379d4eaa6ec24826dd44cd5cf65a3" and I want to see if it is active on the PHP server that has the active session.

This, through another page, external, for example, if someone calls: http://meuenderecom.com.br/getSession.php?idUsuario=400379d4eaa6ec24826dd44cd5cf65a3 I want to return 'S' if the session is active, or 'N' if the session is closed.     

asked by anonymous 01.03.2016 / 17:04

3 answers

5

So I understand, you want to know if a other session, other than that of the user in question, exists, right? If so:

PHP saves session data to a temporary folder on the server, which you can find out which one is, or even set, using session_save_path () .

For each session, PHP creates a sess_{SESSION_ID} file in this folder. You can get the list of files (sessions) using:

<?php
print_r(scandir(session_save_path()));
?>

If you want to know if a specific session exists, if you have the SESSION_ID, you can do the following:

<?php
session_start();
// $SESSION_ID = id da sessão que você quer saber se existe
echo (file_exists(session_save_path().'/sess_'.$SESSION_ID) ? "Existe!" : "Não existe!");
?>

As it looks like you want to search for the 'user', you would have to parse these files and check for the information you need there. If you do not want to do parse , you can get the ID of all sessions, which is in the file name, and loop through initializing via session_start($SESSION_ID) and searching for the data you need to check, in that case the user.

Remember that this is by no means a recommendation. There is still an option, which would be to manipulate the sessions yourself by setting a new handler . That way you could save your data in a bank or whatever way you prefer, but you need to make sure you know what you're doing!

Finally, it looks like you just want to know if a user is online. There are other, much more secure and efficient techniques for doing this, but stay for the next question (or even have one about it).

    
01.03.2016 / 17:54
3

To do this, simply use the isset () command, in your case it would look like this, using an if ternary:

$valor = isset($_SESSION['usuario']) ? 'S' : 'N';
    
01.03.2016 / 17:08
-1

With this question you actually end up expressing perhaps other doubts, ideal to study a little. If you want to get% session% you can use id but there are other variables about it, for example: - You may have closed the session_id() session, but the usuario(session['usuario'] may still be the same if a regenerate was not done ... I recommend you search a little about how sessions work for all of us to help you better.

    
23.12.2016 / 15:58