Use of cookies vs session in PHP


Currently I have a corporate intranet working with session variables, and it does it very well. Today I will start with a project for the general public and I decided to load the datastore on the front-side with cookies. I have never used them and I am confused. My question is: can I use a cookie to store certain data of a user that came from the database?

For example:

$_SESSION["NOMBRE"] = 'Juan Pérez';
$_SESSION["ID"] = 12345;

This has helped me a lot to create my intranet, but I do not understand well if the cookie stores the same data that I need.

asked by Alberto Siurob 17.03.2017 в 22:43

1 answer


The concept is to store persistent data in page loads for a web visitor. The cookies store it directly on the client. The sessions use a cookie as a type of key to associate with the data stored on the server.

It is preferred to use sessions because the actual values are hidden from the client and controlled when the data expires and becomes invalid. If everything was based on cookies, a user (or a hacker) could manipulate their cookie data and then reproduce requests on your site.

Note: I do not think there is any advantage in the use of cookies, apart from simplicity. Look at it this way ... Does the user have any reason to know his ID? Normally, I would say no, the user does not need this information. Giving information must be limited in a need to know base. What happens if the user changes their cookie to have a different ID, how will your application respond? It is a security risk.

Source StackOverflow

Let's see an example as if you could create a cookie with the same data as a session

We created a Cookie

//Supongamos que...
$nombre = 'Juan Pérez';
$id = '12345';

//Creamos nuestra cookie.
setcookie("nombre",$nombre,strtotime( '+30 days' ),"/",false, false);
setcookie("id",$id,strtotime( '+30 days' ),"/",false, false);

Manual setcookie

Get cookie

//Comprobamos si esta definida nuestra cookie y no NULL.
if ( isset($_COOKIE['nombre']) && isset($_COOKIE['id'])) {
    //Obtenemos datos.  
    $nombreCookie = $_COOKIE['nombre'] ?: '';
    $idCookie = $_COOKIE['id'] ?: '';

    echo $nombreCookie;

If you want to destroy a cookie

//Destruir cookie.
setcookie("nombre",$nombre,1,"/",false, false);
setcookie("id",$id,1,"/",false, false);
answered by 17.03.2017 / 23:15