Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
html
http
cookies

How to create cookies in PHP

Educative Answers Team

Cookies

Cookies are small files downloaded by web browsers onto a user’s computer. One of the ways to create cookies is to use PHP.

Creating a Cookie

PHP has a function called, setcookie(name, value, expiry, path, domain, security). name is the name of the cookie, value is the value stored in the cookie, expire is the timestamp after which the cookie cannot be accessed, path sets the path on the server for which the cookie is available, domain specifies which website can use the cookie, and security sets whether or not the cookie requires HTTPS connections to be used.

<?php 
setcookie("Accessed_Shot", "How to Create Cookies in PHP", time() + 7 * 24 * 60 * 60);
?>

This example script sets a cookie called Accessed_Shot to store the value, How to Create a Cookie in PHP. The time() function returns the current time; so, the resulting calculation in the function call returns the time seven days from when the cookie was set. This means that the cookie has an expiration date of seven days from when it is set.

<?php
// Checking whether cookie has been set
if(isset($_COOKIE["Accessed_Shot"])){
    // Using cookie data
    echo "Previously viewed shot: " . $_COOKIE["Accessed_Shot"];
} else{
    // Cookie not set
    echo "No previously viewed shot";
}
?>

This example demonstrates how a cookie is accessed. The $_COOKIE[] variable is a superglobal in PHP used to access cookies. As an associative array, the name (Accessed_Shot, in this example) of the cookie is used in square brackets to access the value. The isset() function checks if the cookie being accessed has been set. Once the presence of the cookie has been established, the program can act accordingly inside the if or else statements.

RELATED TAGS

php
html
http
cookies
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring