How to set cookies and set expiration time?

Asked

Viewed 2,041 times

4

I am with a div where I search only logged in users, in it I am displaying users but each update is inserted new records, gave me the tip to use cookise more never worked with it. the following code is giving the error Warning: Cannot Modify header information - headers already sent by (output Started at line 5

<?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 http://www.w3schools.com/php/php_cookies.asp

  • Put the full code, including the part that puts the names on file, please.

  • No question, you are starting the session with session_start(); first of all in the code?

  • yes, my login system is complete and working normally, this page I am calling her within a div every X seconds

  • 1

    About the error Cannot Modify header information already have question and answer here on the site.

1 answer

4


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

setcookie($usuario, $id_usuario, time() + (60 * 10), "/");

That will make it last for 10 minutes. Already 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 show the users file online if the cookie already exists and if it does not exist, it will automatically create the cookie and write the user name in the users file online

  • really, I will add but it is not saving in txt, and also the error continues, something else this header Location, as I use inside a div I cannot update the entire page

  • There was an error in the code. I tested this on my server and it worked. It was a simple glitch. I edited my message with the new code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.