• In PHP cookie is a small file with a maximum size of 4KB that the web server stores on the client computer.
  • Cookies are typically used to keep track of information such as a username that the site can retrieve to personalize the page when the user visits the website next time.
  • They can only be read from the domain that it has been issued from.
  • In browser cookies are usually set in an HTTP header but JavaScript can also set a cookie directly.
  • In PHP setcookie () function is used to set a cookie.
  • This function needs to be called prior to any output generated by the script otherwise the cookie will not be set.
  • In setcookie () function name parameter is used to set the name of the cookie and value parameter is used to set the value of the cookie.
  • In setcookie () function expire parameter is used to set the expiry timestamp of the cookie after which the cookie can’t be accessed.
  • In setcookie () function path parameter is used to specify the path on the server for which the cookie will be available.
  • In setcookie () function domain parameter is used to specify the domain for which the cookie is available.
  • In setcookie () function security parameter is used to indicate that the cookie should be sent only if a secure HTTPS connection exists.

Syntax

setcookie (name, value, expire, path, domain, security);

Sample Code

<!DOCTYPE html>
<?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>

Output

 

Categorized in: