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);