skip to Main Content

I am trying to add a cookie in my add_cookie.php file like so:

<?php

setcookie("TestCookie", 'epic_test', time()+3600);
exit('cookie set');

But when accessing https://my-site.com/add_cookie.php I do see the "cookie set" text, but the cookie is not in fact set. Why is that? This code is straight from the documentation 🙂

I have also tried adding this code to functions.php file of my theme and the result is the same. Doing like so also doesn’t help:

setcookie("TestCookie", 'epic_test', time()+3600, '/', 'my-site.com');

This is a WordPress website if that matters. Also, I am checking the cookies using a browser extension, but I also tried returning $_COOKIE from php, there is no difference.

2

Answers


  1. Ensure you’re using the correct hooks and that no output is sent before setting the cookie. You can use the ‘init’ action hook to set the cookie:

    add_action('init', function() {
        if (!isset($_COOKIE['TestCookie'])) {
            setcookie("TestCookie", 'epic_test', time() + 3600, '/', $_SERVER['HTTP_HOST']);
        }
    });
    
    Login or Signup to reply.
  2. For wordpress use

    add_action('init', 'set_my_cookie');
    
    function set_my_cookie() {
        if (!isset($_COOKIE['TestCookie'])) {
            setcookie("TestCookie", 'epic_test', time()+3600, '/', 'my-site.com', true, true);
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search