How do I set cookies and set expiration time?

4

I have a div where I search only logged in users, in it I'm displaying the users but every update is inserted new records, gave me the hint of using cookise more never worked with it. the following code is giving the error Warning: Can not modify header information already -

<?php
$id_usuario = $_SESSION['user_id'];
 $usuario = $_SESSION['user_name'];

setcookie($usuario, $id_usuario, time() + (86400 * 30), "/");

if(!isset($_COOKIE[$usuario])) {
echo "Cookie named '" . $usuario . "' is not set!";
} else {
echo "Cookie '" . $usuario . "' is set!<br>";
echo "Value is: " . $_COOKIE[$usuario];
}
?>

Following this tutorial link

    
asked by anonymous 10.02.2016 / 01:07

1 answer

4

On the page where the user logs in, put the following:

  

setcookie ($ user, $ user_id, time () + (60 * 10), "/");

This will last 10 minutes. In the rest of the page, put this:

<?php
ob_start()
$id_usuario = $_SESSION['user_id'];
$usuario = $_SESSION['user_name'];

if(!isset($_COOKIE[online])) {
include('usuariosonline.txt');
} else { 
//grava os dados no arquivo
setcookie(online, $id_usuario, time() + (60 * 10), "/");
$arquivo = fopen("usuariosonline.txt", "a");
fwrite($arquivo, "<p><img src='avatar/".$id_usuario.".jpg'/>".$usuario."</p>\n");
fclose($arquivo);
include('usuariosonline.txt');
}
?> 

This code will display the online users file if the cookie already exists and, if it does not exist, it will automatically create the cookie and write the user name in the online users file

    
10.02.2016 / 01:40