Chose Language:
Author: Admin/Publisher |not checked

PHP Sessions

Sometimes we need to create a website that need sessions to know if a user is logged or not, or other data we need between pages.

session_start()

We can start a session anytime with session_start() or resume the existing one.

<?php
session_start();

Recuerde que las sesiones se utilizan para guardar datos de la sesión mientras esta está abierta.

$_SESSION

An associative array containing session variables available to the current script

php.net

In the following case I can say that I’m assigning ELPEPE value to session name variable

<?php
session_start();
$_SESSION['name']="ELPEPE";

¿When to use session variables?

An example could it be when a user login in our page.

You could save data from the user on $_SESSION, these data could it be the name, a token or something that distinguish the user, so we could know where the user has access.

I not recommend to store personal user data on sessions like password or something like that. Could store email if its necessary but not make it public on your page.

Do not overcharge sessions with sessions variables, please check this article https://debugged.it/blog/stop-using-php-sessions/ made by Janos Pasztor.

In fact using sessions to store anything could be a security problem. In my opinion you should store a token that permits you to identify the user in the lapse of time that session is alive.

Could it be something like this:

In case you need to store: user preferences, zone times or other things store them in the database.

session_destroy()

Destroy all info associated with the actual session but not destroy variables associated with the session, also do not destroy the session cookie.

If we call session_start() again after a session_destroy() we can access $_SESSION[‘name’] value because we do not unset it.

To eliminate this data we can use unset()

<?php
session_start();
unset($_SESSION['name']);
session_destroy();

In this way we can eliminate $_SESSION[‘name’] variable

IMPORTANT: Never use unset on $_SESSION.

Session functions

1- session_name (since PHP 4)— obtain or establish the actual session name

2- session_id (since PHP 4)— obtain or establish the actual session id

3- session_cache_expire (since PHP 4.2)

4- session_abort(since PHP 5.6.0 and PHP 7) discard all changes in session array and end the session

5- session_gc (since PHP 7.1)— session garbage collection

Deprecated Functions

$HTTP_SESSION_VARS Contain all variables in session, instead use $_SESSION

session_is_registered – we can check a session with isset() so this function has no sense

session_register – Register one or more global variables with the current session actually we use $_SESSION[‘var_name’]

session_unregister -actually we use unset()

Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category