SetCookie with GET method

I was struggling with the correct position to setcookie() in my WordPress site, and I finally made it work by placing it at the very first line of my header.php. But I need it to build the cookie with values gotten from the url of a specific page, that is not the home page. So, the first line of my header.php is:

<?php setcookie( 'mycookie', $_GET["var1"]."/".$_GET["var2"]."/".$_GET["var3"], strtotime( '+5 years' ), COOKIEPATH, COOKIE_DOMAIN, false, false);?>

Read More

I was expecting that when I go to the http://www.example.com/?var1=01&var2=02&var3=03, the cookie would be set to have value “01/02/03” but it just receives the same value as in any other page, “//”, like it is not seeing the variables gotten by $_GET[].

Any idea about how could I make this work?

Related posts

Leave a Reply

2 comments

  1. After some testing with your code, I made a few changes to it in order to debug it a little easier.

    I noticed you wrote down “COOKIEPATH, COOKIE_DOMAIN,” as parameters, I don’t know if you are using it literaly but try replacing them with “/” and “.example.com” to make the cookie available to your whole domain or restrict if necessary.
    That made it work on my server running PHP 5.3.x.

    Note the cookie is created on the first time the page is run, but is only available from the second time the page is loaded onwards.

    The first time you load the page you should see something like:

    Cookie was Saved
    1
    01
    02
    03
    Cookie mycookie does not exist… yet

    The second time it should be like:

    Cookie was Saved
    1
    01
    02
    03
    01/02/03

    Hope I could help.

    <?php
    $cookieName = "mycookie";
    $cookieIsSaved = setcookie( $cookieName,
            $_GET["var1"]."/".$_GET["var2"]."/".$_GET["var3"],
            strtotime( "+5 years" ),
            "/",
            ".example.com",
            false,
            false);
    
    if ($cookieIsSaved) {
      echo "Cookie was Saved<br/>";
    }
    else
    {
      echo "Cookie was not Saved<br/>";
    }
    
    echo $cookieIsSaved."<br/>";
    echo($_GET["var1"]."<br/>");
    echo($_GET["var2"]."<br/>");
    echo($_GET["var3"]."<br/>");
    
    if (isset($_COOKIE[$cookieName])) {
      print_r($_COOKIE[$cookieName])."<br/>";
    }
    else
    {
      echo "Cookie $cookieName does not exist... yet";
    }
    ?>
    
  2. I guess you should use the query_vars[] sub-array of the $wp_query object:

    global $wp_query;
    if (isset($wp_query->query_vars['var1'])) {
        // modify the where/join/groupby similar to above examples
    }
    

    or simply the get_query_var() function.