This line of yours has a problem:
$estilo_cor = setcookie('cor_estilo', 'padrao', (time() + (2 * 3600)));
She won’t take the value of cookie set, only one true or false.
See a solution that assigns value to the variable for the current page and to the cookie:
<?php
global $estilo_cor;
if( isset( $_COOKIE['cor_estilo'] ) ) {
$estilo_cor = $_COOKIE['cor_estilo'];
} else {
$estilo_cor = 'padrao';
setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
}
?>
If the cookie is set, we use its value. Otherwise, set $estilo_cor and creates a cookie with what has been defined.
By the way, it would be nice to set a default for the name of things, you’re using $estilo_cor, and 'cor_estilo'. It may even work, but it only causes confusion to keep a code like this (PHP is enough, which is all inconsistent).
Taking out the global:
In fact, in this case it is even dangerous to do this way, because it creates the illusion that you can call the function in other parts of the code, which is not true because it is a cookie, but stands as an example of how to use something from another source without global:
css_cookie_check.php
<?php
function getStyle() {
if( isset( $_COOKIE['cor_estilo'] ) ) {
$estilo_cor = $_COOKIE['cor_estilo'];
} else {
$estilo_cor = 'padrao';
setcookie( 'cor_estilo', $estilo_cor, ( time() + ( 2 * 3600 ) ) );
}
return $estilo_cor;
}
?>
And in the main PHP:
<?php
require('/style/css_cookie_check.php');
$estilo_cor = getStyle();
?>
In fact, in your case, I would need neither my example nor global, but left to illustrate.
Cookies cannot be used at exactly the same time they are created. They only assume after the page is reloaded. This is standard. This @Bacco tip should solve, because when it does not exist, in addition to setting the cookie, it already sets in the variable the default value (which can be used in the first access).
– Clayderson Ferreira
Clayderson Ferreira, did not know this cookie. Thanks man
– Alê Moraes
Too much man, thanks!!!
– Alê Moraes
This PHP scope business is kind of boring. I avoid using it as much as possible
global. Global reminds me classic ASP variable scope, gives chills.– Bacco