1

I created this Cookie alert bar for my site, it works as intented. But you need to click the close link twice to close down the warning for some reason that I cannot figure out.

I use this following function to check if cookie exists or not.

function checkIfCookieExist($cookieName) {
    if(isset($_COOKIE[$cookieName])) {
        return true;
    }
    else {
        return false;
    }
}

if cookie does not exist, and the cookie get parameter exists and equals 1 I create a cookie

if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
    $cookieName     = 'cookieConfirmation';
    $cookieValue    = 'Cookie confirmation';
    $cookieDuration = 86400 * 30 * 3;
    setcookie($cookieName, $cookieValue, time() + $cookieDuration); 
}

Prints out the cookie bar, links to index with a get parameter for the cookie

function renderCookieBar() {
echo('
    <div id="cookieBar">
        <p>blabla cookie, cookies on this site yo</p>
        <a href="index.php?cookie=1">I understand, close this box!</a>
    </div>
    ');
}

Calls function to print out cookiebar at given place in my html code

if(!checkIfCookieExist('cookieConfirmation')) {
                renderCookieBar();
}

I appreciate any answers or help,

Cheers!

1 Answers1

1

When you set the cookie in the header, the cookie is not directly present; means: the cookie is available up on the next page hit.

Check the manual: http://php.net/set_cookie

Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array. Cookie values may also exist in $_REQUEST.

You can either

1. Set the cookie and immediately reload the page

Set the cookie and force a browser refresah by using header("Refresh:0");.

if (!checkIfCookieExist('cookieConfirmation') && isset($_GET['cookie']) && $_GET['cookie'] == 1) {
    $cookieName     = 'cookieConfirmation';
    $cookieValue    = 'Cookie confirmation';
    $cookieDuration = 86400 * 30 * 3;
    setcookie($cookieName, $cookieValue, time() + $cookieDuration); 
    header("Refresh:0");
}

2. Use Javascript

When setting the cookie with JavaScript it is directly available from the browser. You may also rewrite your script, so the JavaScript sets the cookie and removes the notification bar.

There are many solutions (also here on SO) how to work with cookies in JavaScript easily. If you are using a JavaScript library like jQuery you also have plugins handling the cookies.

Community
  • 1
  • 1
secelite
  • 1,353
  • 1
  • 11
  • 19