CyanCoding
CyanCoding

Reputation: 1037

How to change CSS with PHP and create a cookie in the same place

So, I have a bit of code and it basically checks to see if a cookie is created and if it is, then set an element to display: none; and if it isn't, then set an element to display: block; and create a cookie (this way, as long as the cookie remains, the display will only change that first time).

Unfortunately, I ran into a dilemma and I think I know why. I know cookies have to be called before all other things relating to HTML. But any CSS has to change in the head or the body (in this case, the body). So, I am wondering how I can get this done and if it isn't possible/isn't a good idea, what a better solution might be.

Also, I thought about having it check if the cookie has been created before and do the whole cookie-creating part and then later on have the it check to see if the cookie exists and if it doesn't, change the element to display: block;, but this wouldn't work because it would create a cookie the first time it went to the page before it even changed the CSS.

Code:

if(isset($_COOKIE["beenToCyanCoding"])) {
    echo '
        <style type="text/css">
            #welcomeToCyanCoding {
                display: none;
            }
        </style>';
}
else {
    echo '
        <style type="text/css">
            #welcomeToCyanCoding {
                display: block;
            }
        </style>';
    setcookie("beenToCyanCoding", date("m/d/y"), time() + 10 * 365 * 24 * 60 * 60, "/");
}

Upvotes: 1

Views: 1147

Answers (2)

Jonny
Jonny

Reputation: 1329

Use a variable then echo it in the head like this.

if(isset($_COOKIE["beenToCyanCoding"])) {
$style= "<style type=\"text/css\">#welcomeToCyanCoding {display:none;}</style>";
} else {
$style= "<style type=\"text/css\">#welcomeToCyanCoding {display: block;}</style>";
setcookie("beenToCyanCoding", date("m/d/y"), time() + 10 * 365 * 24 * 60 * 60, "/");
}

And in your head

<head><?php echo $style; ?></head>

Upvotes: 2

hans-k&#246;nig
hans-k&#246;nig

Reputation: 553

<?php
 // At the top of the page
 if(!isset($_COOKIE["beenToCyanCoding"])){

     // Create cookie only if it does not exist
     setcookie("beenToCyanCoding", date("m/d/y"), time() + 10 * 365 * 24 * 60 * 60, "/");

     // Save the cookie to a variable. Use the variable 
     // to display either none or block in the CSS defination.
     $cookie_exist = $_COOKIE["beenToCyanCoding"];

 }
?>

 <style type="text/css">
    #welcomeToCyanCoding{
        display: <?php if(isset($cookie_exist)){ echo 'none'; }else{ echo 'block'; } ?>;
    }
 </style>

Upvotes: 1

Related Questions