I'm having some trouble firing cookies on the condition of what page the user visits first.
Code below fires a cookie if on pages 2641, 2998, 2949 and no cookie exists. However, how do I do it to fire a different cookie if user is on any other page on the website if no cokkies exist?
Rule: Two cookies cannot exist. Just one or the other.
Any help much appreciated :)
if (is_page([2641,2998,2949]) && !isset($_COOKIE['ppc_campaign']) && !isset($_COOKIE['organic'])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
}
Sounds like this is what you want. Check for cookie existence. If neither exists, check the specific page, otherwise do something else.
if (!(isset($_COOKIE['ppc_campaign']) || isset($_COOKIE['organic']))) {
if (is_page([2641,2998,2949])) {
$ppc_cookie = "ppc_campaign";
$ppc_value = (!empty($_SERVER['HTTPS']))
? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI']
: "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$path = "/";
setcookie($ppc_cookie, strstr($ppc_value, '?'), time() + (86400 * 28), $path);
$acf_applicationLink = $ppc_value;
}
else {
$organic_cookie = "organic";
$organic_value = "?campaign=_ORGANIC_";
$path = "/";
setcookie($organic_cookie, $organic_value, time() + (86400 * 28), $path);
$acf_applicationLink = $organic_value;
}
}
Related
I am trying to delete a cookie by setting that cookie in past time:
$cookie_name = "user";
$cookie_value = "david";
//subtraction from time causes deletion of cookie
setcookie($cookie_name, $cookie_value, time() - (86400 * 30), "/");
With the below code I try to check whether cookie is enabled or not and it returns if case rather than else part, while I already dell that cookie:
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
But the else part is not working when we delete cookie and I don't know why?
The main problem is you just set user cookie time to past date not all the other cookie in super global $_COOKIE array . Try like this way to set for all $_COOKIE value using foreach() to past date and then check count condition.
<?php
$cookie_name = "user";
$cookie_value = "david";
$past_time = time() - 3600;
//use look set all cookie time to past date.
foreach ( $_COOKIE as $key => $value )
{
setcookie( $key, $value, $past_time, '/' );
}
//counting number of cookies
if(count($_COOKIE) > 0) {
echo "<br>Cookies are enabled/exists";
} else {
echo "<br>Cookies are disabled/not exists";
}
?>
DEMO: https://3v4l.org/jvRXW
I tried many ways to set a cookie, but when I get the cookie the value's not set. My code is placed before the <!DOCTYPE html>:
<?php
$url = explode('/', $_GET['url']);
$ref = $url[1];
$cookie_name = "refid";
$cookie_value = $ref;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0);
?>
The $url[1] is set, I can see it in print_r() the problem is getting the cookie from a different page the calling code is:
<?php
if (!isset($_COOKIE['refid'])) {
echo "<br/>Cookie named refid is not set!";
} else {
echo "<br/>Cookie refid is set!<br>";
echo "Value is: " . $_COOKIE['refid'];
}
?>
Please help to resolve my problem.
Add this line:
$_COOKIE[$cookie_name] = $cookie_value;
after you set the cookie:
<?php
$url=$_GET['url'];
$url=explode ('/',$_GET['url']);
$ref=$url[1];
$cookie_name = "refid";
$cookie_value = $ref;
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/", "", 0);
$_COOKIE[$cookie_name] = $cookie_value;
?>
The setcookie() does not update the current $_COOKIE variable, which will be instantiated when the script loads. The variable will first be updated next time you load the script.
I have an age gate set up on my site, so that users under 17 can't enter the site, but I want people, who have bookmarked a specific link to be able to go to that link after passing through the age gate:
Here is my age gate code:
<?php
session_start();
if(isset($_SESSION['legal'])) { # Check to see if session has already been set
$url = ($_SESSION['legal'] == 'yes') ? 'index.php' : 'message.php';
header ('Location: ' .$url);
}
// If visitor hasn't gone through the age gate - Age Gate function and Set Session//
if(isset($_POST['checkage'])) {
$day = ctype_digit($_POST['day']) ? $_POST['day'] : '';
$month = ctype_digit($_POST['month']) ? $_POST['month'] : '';
$year = ctype_digit($_POST['year']) ? $_POST['year'] : '';
$birthstamp = mktime(0, 0, 0, $month, $day, $year);
$diff = time() - $birthstamp;
$age_years = floor($diff / 31556926);
if($age_years >= 18) {
$_SESSION['legal'] = 'yes';
$url = 'index.php';
} else {
$_SESSION['legal'] = 'no';
// If failed the Age Gate go to specific page
$url = 'message.php';
}
header ('Location: ' .$url);
}
?>
What can I add to this code so that if I wanted to go to domain/page.php or domain/subdirectory/ -- the Age Gate will take me there after I pass it? (I know I have to use HTTP Referrer, but I can't figure out how to include it).
Edit to Add : I know that sometimes Browsers will not keep/send the HTTP Referrer, so I will need a solution for those who don't pass that value.
EDIT : AGE Calculation based on the form submission -
$day = ctype_digit($_POST['day']) ? $_POST['day'] : '';
$month = ctype_digit($_POST['month']) ? $_POST['month'] : '';
$year = ctype_digit($_POST['year']) ? $_POST['year'] : '';
$birthstamp = mktime(0, 0, 0, $month, $day, $year);
$diff = time() - $birthstamp;
$age_years = floor($diff / 31556926);
I'd setup this the other way around: have each page set a $_SESSION variable to indicate where to go:
if (!isset($_SESSION['legal']) || $_SESSION['legal'] == 'no') {
$_SESSION['target'] = $_SERVER['PHP_SELF'];
header('Location: message.php');
return;
}
// continue script execution...
And in your message.php:
$isLegal = check_age(); // your age checking logic
if ($isLegal && isset($_SESSION['target'])) {
header('Location: ' . $_SESSION['target']);
} else if ($isLegal) {
header('Location: index.php');
} else {
// setup message.php with a validation failed message
}
Mind, this is just one of the possible variations, but I'd suggest not relying on user data such as the referrer (some browser extensions even explicitly unset/modify that).
i have this code im trying to do for a type of cache system so it remembers the city the user has selected. if the user has selected a city it stores it in sessions and cookies, and will automatically redirect them to the city page if they've selected it before.
sessions work fine, but it doesn't seem to be setting the cookie to an empty value if the $_GET['city'] variable is empty...
heres my code:
function gen_url ($city)
{
$url = 'http://www.mysite.com';
if (!empty($city)) $url .= "/c-$city";
return $url;
}
function set_cache ($variable, $value)
{
$_SESSION[$variable] = $value;
setcookie($variable, $value, time() + 31536000);
}
$redirect = false;
$redirect_array['city'] = '';
if (!empty($_GET['city']))
{
$sql = mysql_query("select * from `cities` where `slug`='".mysql_real_escape_string($_GET['city'])."'");
if (mysql_num_rows($sql) != 0)
{
while ($row = mysql_fetch_assoc($sql))
{
foreach ($row as $k => $v)
$city[$k] = $v;
}
$redirect_array['city'] = $city['slug'];
}
else
{
$redirect = true;
}
}
if ($redirect)
{
header('Location: '.gen_url($redirect_array['city']);
die();
}
set_cache('city', $redirect_array['city']);
You can't set a cookie with an empty string as it will delete the cookie.
From the docs:
If the value argument is an empty string, or FALSE, and all other
arguments match a previous call to setcookie, then the cookie with the
specified name will be deleted from the remote client.
You can't set a cookie to most falsy values to indicate falseness of a trit cookie. Only '0' will work. Use that.
PHP's setcookie() doesn't allow you to set cookies with empty values. But you can do that with header()
replace:
setcookie($variable, $value, time() + 31536000);
with:
header('set-cookie: '.rawurlencode($variable).'='.rawurlencode($value).'; max-age=31536000', false);
You can set empty value to the cookie by using null pointer as the value
like this:
setrawcookie('testEmptyCookie', "\x00", time() + 3600, '/');
(tried on php 5.6, 7.2)
Make sure to set your cookie with a negative time:
setcookie($variable, '', -1);
I got it working on others but on (Firefox the most important one), it doesn't work. What's wrong in my code ? or what's wrong with Firefox :)
if($_COOKIE['ea1']){
die ("cookies set");
} else {
setcookie('ea1',1,time()+24*60*60);
}
try this:
if($_COOKIE['ea1']){
die ("cookies set");
} else {
setcookie('ea1',1,time()+24*60*60,'/','example.com');
}
you might also think of clearing your browsers cookies before
EDIT: if you are on localhost you might have to use
setcookie('ea1',1,time()+24*60*60,'/',false);
This will work
//Set_Cookie('mycookie', 'visited 9 times', 30, '/', '', '');
function Set_Cookie(name, value, expires, path, domain, secure) {
if (!hasKey()) {
return;
}
var today = new Date();
today.setTime(today.getTime());
if (expires) {
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date(today.getTime() + (expires));
document.cookie = name + "=" + escape(value) +
((expires) ? ";expires=" + expires_date.toGMTString() : "") +
((path) ? ";path=" + path : "") +
((domain) ? ";domain=" + domain : "") +
((secure) ? ";secure" : ""); }
function Get_Cookie(check_name) {
var a_all_cookies = document.cookie.split(';');
var a_temp_cookie = '';
var cookie_name = '';
var cookie_value = '';
var b_cookie_found = false;
for (i = 0; i < a_all_cookies.length; i++) {
a_temp_cookie = a_all_cookies[i].split('=');
cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
if (cookie_name == check_name) {
b_cookie_found = true;
if (a_temp_cookie.length > 1) {
cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
}
return cookie_value;
break;
}
a_temp_cookie = null;
cookie_name = '';
}
if (!b_cookie_found) {
return null;
} }
I've had issues sometimes with cookies and redirects. Make sure you're setting your Location header BEFORE you're Set-Cookie header for maximum browser compatibility.
Had same problem, this worked for me:
Set a cookie on localhost, use false
setcookie("TestCookie", $value, time()+3600, "/", false);
To delete same cookie use negative time
setcookie("TestCookie", '', time()-3600, "/", false);