How To Handle Cookies In PHP Using setcookie()

tutorial to PHP set cookies

Cookies are an essential component of web development, allowing developers to store small pieces of data on the user’s browser. In this tutorial, you will learn how to handle cookies in PHP using the setcookie() function, including setting, accessing, modifying, and deleting cookies effectively.

1. PHP setcookie() Function to Set or Create Cookies

The PHP setcookie() function is used to set or create cookies. This function has 7 parameters, but only the name parameter is required, and the others are optional.

setcookie(name, value, expires, path, domain, secure, httponly)
ParameterDescription
name (Required)With the cookie name, you can access the cookie value.
valuevalue of the cookie. The default value is empty.
expiresThe time the cookie expires. If you do not define the cookie will not be removed until the browser cache is cleared.
pathIt defines which pages can access this cookie.
domainDomain-level cookie accessibility. Suppose you have a domain name that is example.com and to make the cookie available on all subdomains of example.com, set the domain to “example.com”. “www.example.com” will make the cookie available only to the www subdomain.
secureIt takes a boolean value (true or false). If it is true the cookie should only be transmitted over a secure HTTPS connection from the client.
httponlyCookies can also be accessed on the client side using JavaScript, but if you pass true to this parameter, the cookie will not be accessible by JavaScript.

Here is an example to set or create cookies using the setcookie() function:

<?php
$cookie_name = "username";
$cookie_value = "Rahul";

setcookie($cookie_name, $cookie_value);
PHP create cookies using the setcookie function

2. Get the Cookie Values using PHP

Once cookies are set, PHP allows developers to access them using the $_COOKIE superglobal array. This array contains all the cookies sent by the client in the current request. To access a specific cookie, simply use its name as the key:

<?php
// Access the value of the 'username' cookie
$userName = $_COOKIE['username'];
echo $userName ; // Output: Rahul

3. Set Cookies with the Expiry Time

The third parameter of the setcookie() function takes the expiration time of the cookie. If not specified, the cookie will expire when the browser session ends.

The expiration time must be in Unix timestamp. Therefore we will use the time() function, this function returns the current Unix timestamp. Here are some examples:

  • time()+60 = after 1 minute.
  • time()+60*2 = after 2 minute.
  • time()+60*60 = after 1 hour (60*60 = 3600 seconds).
  • time()+60*60*24 = after 24 hours or one day.
  • time()+60*60*24*9 = after 9 days.
<?php
$cookie_name = "username";
$cookie_value = "Rahul";
$expire = time() + 60; // after 60 seconds

setcookie($cookie_name, $cookie_value, $expire);

Alternative Syntax of the setcookie() introduced in PHP 7.3.0

This alternative syntax allows developers to specify cookie attributes using an array parameter instead of passing multiple arguments to the setcookie() function. Let’s explore this alternative syntax:

setcookie(name, value, array options[])
<?php
$options = [
    'expires' => time() + 3600, // Expires in 1 hour
    'path' => '/', // Available on the entire domain
    'domain' => 'example.com', // Domain where the cookie is available
    'secure' => true, // Only transmitted over HTTPS
    'httponly' => true // Accessible only via HTTP requests
];

setcookie('user', 'JohnDoe', $options);

4. Checking Whether the Cookie has been Set

The setcookie() functoin will return true if the cookie has been set.

<?php
$cookie_name = "user";
$cookie_value = "Jane";
$expire = time() + 60;

$myCookie = setcookie($cookie_name, $cookie_value);

// Check if the cookie was set successfully
if ($myCookie) {
    echo "The cookie has been sent successfully.";
} else {
    echo "Oops!, Something is going wrong.";
}

5. Modify Cookies in PHP

To modify a cookie in PHP, you can simply set it again using the setcookie() function with the updated values. It’s essential to note that to modify a cookie, you need to set the same name with new values. For example:

<?php
// Modify the value of the 'user' cookie
setcookie('user', 'JaneDoe', time() + 3600, '/');

6. Delete Cookies in PHP

You can delete a cookie by setting the expiration time of the cookie to a time in the past. This instructs the browser to remove the cookie from its storage. Here’s how you can delete a cookie in PHP:

<?php
// Delete the 'user' cookie
setcookie('user', '', time() - 3600, '/');

7. Best Practices

When working with cookies in PHP, it’s essential to follow best practices to ensure security and efficiency:

  • Keep sensitive information secure: Avoid storing sensitive information such as passwords or personal details in cookies. If necessary, encrypt the data before storing it.
  • Set appropriate expiration times: Set expiration times for cookies based on your application’s requirements. Expire cookies when they are no longer needed to reduce unnecessary data storage on the client’s browser.
  • Use HTTPS: When dealing with sensitive data in cookies, always transmit cookies over HTTPS to encrypt the data in transit and prevent eavesdropping.
  • Sanitize input: If cookies contain user-generated data, always sanitize and validate the input to prevent security vulnerabilities such as XSS (Cross-Site Scripting) attacks.
  • Limit cookie size: Keep cookies as small as possible to minimize the impact on network performance and ensure compatibility with various browsers.

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies to ensure that we give you the best experience on our website. Privacy Policy