Función PHP setcookie()
Ejemplo
El siguiente ejemplo crea una cookie llamada "usuario" con el valor "John Doe". La cookie caducará después de 30 días (86400 * 30). El "/" significa que la cookie está disponible en todo el sitio web (de lo contrario, seleccione el directorio que prefiera).
Luego recuperamos el valor de la cookie "usuario" (usando la variable global $_COOKIE). También usamos la función isset() para averiguar si la cookie está configurada:
<!DOCTYPE html>
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Definición y uso
La función setcookie() define una cookie que se enviará junto con el resto de los encabezados HTTP.
Una cookie se utiliza a menudo para identificar a un usuario. Una cookie es un pequeño archivo que el servidor incrusta en la computadora del usuario. Cada vez que la misma computadora solicite una página con un navegador, también enviará la cookie. Con PHP, puede crear y recuperar valores de cookies.
El nombre de la cookie se asigna automáticamente a una variable del mismo nombre. Por ejemplo, si se envió una cookie con el nombre "usuario", se crea automáticamente una variable llamada $usuario, que contiene el valor de la cookie.
Nota: La función setcookie() debe aparecer ANTES de la etiqueta <html>.
Nota: El valor de la cookie se codifica como URL automáticamente cuando se envía la cookie y se decodifica automáticamente cuando se recibe (para evitar la codificación de URL, use setrawcookie() en su lugar).
Sintaxis
setcookie(name, value, expire, path, domain, secure, httponly);
Valores paramétricos
Parameter | Description |
---|---|
name | Required. Specifies the name of the cookie |
value | Optional. Specifies the value of the cookie |
expire | Optional. Specifies when the cookie expires. The value: time()+86400*30, will set the cookie to expire in 30 days. If this parameter is omitted or set to 0, the cookie will expire at the end of the session (when the browser closes). Default is 0 |
path | Optional. Specifies the server path of the cookie. If set to "/", the cookie will be available within the entire domain. If set to "/php/", the cookie will only be available within the php directory and all sub-directories of php. The default value is the current directory that the cookie is being set in |
domain | Optional. Specifies the domain name of the cookie. To make the cookie available on all subdomains of example.com, set domain to "example.com". Setting it to www.example.com will make the cookie only available in the www subdomain |
secure | Optional. Specifies whether or not the cookie should only be transmitted over a secure HTTPS connection. TRUE indicates that the cookie will only be set if a secure connection exists. Default is FALSE |
httponly | Optional. If set to TRUE the cookie will be accessible only through the HTTP protocol (the cookie will not be accessible by scripting languages). This setting can help to reduce identity theft through XSS attacks. Default is FALSE |
Detalles técnicos
Valor devuelto: | VERDADERO sobre el éxito. FALSO en falla |
---|---|
Versión PHP: | 4+ |
Registro de cambios de PHP: | PHP 5.5: se incluyó un atributo Max-Age en el encabezado Set-Cookie enviado al cliente PHP 5.2: se agregó el parámetro httponly |
Más ejemplos
Ejemplo
Varias fechas de caducidad de las cookies:
<?php
$value = "Hello world!";
// cookie will expire when the browser close
setcookie("myCookie", $value);
// cookie will expire in 1 hour
setcookie("myCookie", $value, time() + 3600);
// cookie will expire in 1 hour, and will only be available
// within the php directory + all sub-directories of php
setcookie("myCookie", $value, time() + 3600, "/php/");
?>
<html>
<body>
...some code...
</body>
</html>
Ejemplo
Para modificar una cookie, simplemente configure (nuevamente) la cookie usando la función setcookie():
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Ejemplo
Para eliminar una cookie, use la función setcookie() con una fecha de vencimiento en el pasado:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Ejemplo
Cree un pequeño script que verifique si las cookies están habilitadas. Primero, intente crear una cookie de prueba con la función setcookie(), luego cuente la variable de matriz $_COOKIE:
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
❮ Referencia de la red PHP