I have a PHP function that uses $_GET to grab ‘utm_source’ from the URL and set it in a cookie.
<?php
if(!isset($_COOKIE['utm_src'])) {
$utm_src = $_GET['utm_source'];
setcookie("utm_src", $utm_src, 0, "/");
}
?>
This all happens before any HTML is sent through (in functions.php using WordPress), and seems to be writing properly when I check the cookies after page load.
The issue occurs when I try to echo the variable into a javascript console.log in order to make sure everything is working properly:
<?php
$utm_src = $_COOKIE['utm_source'];
echo "<script>console.log('utm is $utm_src');</script>";
?>
The strange thing is that when I view source the script seems to be written correctly including the variable, yet not in the console.
This is what shows in the actual source after page load:
<script>
console.log('utm is utm-name-here');
</script>
However, the console only shows ‘utm is ‘, with no variable. I was hoping to use the cookie variable to determine whether a script should be echo’d onto page or not.
You are storing your cookie as
utm_src
and trying to access it asutm_source
Use the same name when setting the cookie and when reading the cookie and you’ll get the result that you’re hoping for.
Specifically
should be