I'm having two issues with setting and retrieving cookies.
Cookie gets loaded but can't be called until page is refreshed. Meaning that the cookie shows up in developer tools but not when trying to use its value on the page. The value does seem available to use on page after refreshing.
Cookie is not available across entire domain and subdirectories. For example, if the user enters at http://example.com/sub/ the goes to http://example.com/, the cookie gets destroyed.
Here's my code:
$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
setcookie('ad_source',$ad_source,$date_of_expiry,'/');
if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
echo '... do something else';
}
I'm trying to to show different information throughout entire site by determining what adwords campaign the user clicked in on.
I don't usually use cookies and prefer to set a session, but in this case I want be able to track the source for a longer amount of time.
Everything is working as expected now. A little more insightful information into cookies at this post helped a lot.
PHP cookie set in second refresh page
Redirect user to page after cookie is set. Second request from browser sends cookie, server returns info relative to its value.
Check to see if $ad_source is set before creating cookie.
The updated code:
$ad_source = $_GET['source'];
$date_of_expiry = time() + (86400 * 7);
if ( $ad_source ) {
setcookie('ad_source',$ad_source,$date_of_expiry,'/','example.com');
if ( $_COOKIE['ad_source'] == 'adwords_campaign_01' ) {
header( 'Location: http://example.com/' );
echo '... do something';
} elseif ( $_COOKIE['ad_source'] == 'adwords_campaign_02' ) {
header( 'Location: http://example.com/' );
echo '... do something else';
}
}
Related
Why?
I'm attempting to setup an Adword Campaign with my WordPress website, pretty easy stuff but I want to be able to SWITCH contact forms depending if they visited the site using AdWords or Bing/Google SERPS.
So the idea is that if they visit https://example.com/landing-page/ they will reach a page with different contact numbers and email form that has a title indicating that they have come from Adwords, all straight forward, but then, if they click the menu bar away from the landing page, they will get standard numbers and standard email forms, which makes the tracking process a little bit harder.
Setting the temporary cookie
So by using custom WordPress page template files, and when a visitor visits the landing page, it sets a cookie using:
<?php
// 60 Seconds, live environment set to 6000 (1 hour)
$date_of_expiry = time() + 60 ;
setcookie( "adwords-customer", "adwords-visit", $date_of_expiry );
?>
Checking the cookie and do A or B
Then throughout the rest of the website (not present on the landing page) it will check if the cookie is present, and if present it does A, if not it does B, here's the code:
<?php
if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
echo "cookie set";
} else {
echo "cookie not set";
}
?>
The Problem
The results are always "cookie set" and never else echo "cookie not set", thanks for any help in advance.
You see the ! here?
if(!isset($_COOKIE['adwords-customer']) || ($_COOKIE['adwords-customer'] != 'true')){
^
echo "cookie set";
} else {
echo "cookie not set";
}
It means that you're checking if it is NOT set, so that should be removed or invert the echos.
And the != 'true' make sure you're not checking for boolean. If so, remove the quotes.
Try giving this code a go!
if(isset($_COOKIE['adwords-customer']) && ($_COOKIE['adwords-customer'] == true)){
echo "cookie set";
} else {
echo "cookie not set";
}
If you find it now works but only on the URL that sets the cookie then ensure that your setcookie is set using / to indicate the entire domain, rather than just the /path/, e.g:
$value = 'adwords-visit';
setcookie("adwords-customer", $value);
setcookie("adwords-customer", $value, time()+60);
setcookie("adwords-customer", $value, time()+60, "/");
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>
I understand, close this box!
</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!
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.
I have a landing page, that sets a cookie whenever a user enters the page. If this cookie is set, it redirects the user to my homepage. The problem is that if my user wants to enter the landing page again and they already have this cookie set, it will automatically redirect them to the homepage. My domain will be set on the landing page, meaning that every time a user enters my site they will see this page.
Is there a way to dynamically allow access to the landing page with the cookie? My users should be able to enter the landing page at will; however I also want the users to be directed to my homepage if they are directly entering my website.
Here's my code:
PHP:
<?php
$time = time() + (60 * 60 * 24);
if (isset($_COOKIE['landing'])) {
header('Location: home.php');
} else {
setcookie("landing", true, $time);
}
?>
Well, you could use a query parameter, eg. index.php?noredirect=1, and in your script:
if(isset($_COOKIE['landing']) && $_GET['noredirect'] != 1) {
header('Location: home.php');
} else if(!isset($_COOKIE['landing'])) {
setcookie('landing', true, $time);
}
Now if you append ?noredirect=1 to the url, the user will not be redirected, but by default they will (if the cookie is set).
You need to know if the user wants to stay or not. So you will have to set a variable or something like this.
if ( isset( $_COOKIE['landing'] ) && !$user_wants_to_stay ) {
header( "Location: home.php" );
} else {
...
}
You could use the session or a second cookie which will be set via javascript or simply a get variable in the URL
I have a site where the phone number in the header file needs to change depending on the referrer. If someone comes to the site via google, for example, the phone number is different that if they came directly to the site.
I have it working, except for when the user goes to a different page on the site. The code checks the referrer and changes the number to the direct number.
What I want is for the number to be set by the referrer the first time the user visits the site, and for it not to change. I imagine cookies or sessions are the way to go here, I"m just not sure how the code should be structured.
if (!empty($_SERVER['HTTP_REFERER'])) //user has come via search engine or a page within our site
{
$referer = $_SERVER['HTTP_REFERER'];
if (strpos($referer,'google') !== false) {
$callin_number='1-444-444-4444';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
elseif (strpos($referer,'bing') !== false) {
$callin_number='1-111-111-1111';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
else {
$callin_number='1-222-222-2222';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
}
else { //user has come directly to site
$callin_number='1-333-333-3333';
$callin_dialer=preg_replace("/[^0-9,.]/", "", $callin_number);
}
If you want to use session or cookie:
semi-pseudo:
<?php
session_start();
if ( !isset( $_SESSION['referer'] ) )
{
put your code here, and put whatever you need to session:
$_SESSION['referer'] = ...
$_SESSION['dialin'] = ....
}
and use $_SESSION['referer etc'] in your code instead of $referer etc.
$_SESSION['referer etc'] will be available on the next page load,
the IF condition above will be false on the next page load.
Cookies are just a bit different: http://php.net/manual/en/function.setcookie.php
I have this platform which you can login and do your tests (this is a test link): www.mf.pt.la
I can't understand why this isn't working... first I tried this on top of my config.php file:
ini_set('session.cookie_lifetime', 864000);
ini_set('session.gc_maxlifetime', 864000);
Than I tried this with a cookie:
$year = time() + 31536000;
if($_POST['remember']=="1")
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
elseif($_POST['remember']=="")
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}
None seem to work because after 30mins/1h user is logged out! :(
This is very frustrating because inside this website users are usually getting in a out more than once per day, and having always to login is making me lose users actually! :(
EDIT 1:
Ok, so let's see where we are at this point.
After a lot of tests, I have noticed the problem was that I was trying to save an array directly into the cookie and it doesn't work like that. I have searched a lot and created a very simple cookie with name "test" and content "text" and it worked, so if what was working I did created a cookie!
Then I searched for a way to put it working all together on the same cookie instead of save one cookie for each information I needed.
So this is the conclusion. To create the cookie, this is what I've made:
$cookie_name = "remember_me";
$userinfo = $_SESSION[LOGIN_USER]['user_id']."_".$_SESSION[LOGIN_USER]['user_type']."_".$_SESSION[LOGIN_USER]['name']."_".$_SESSION[LOGIN_USER]['email'];
if($_POST['remember']=="1"){
setcookie($cookie_name, $userinfo, time() + 31536000, '/');
}else{
setcookie($cookie_name, $userinfo, time() + 864000, '/');
}
And to call the cookie this is what I have made:
if(isset($_COOKIE["remember_me"])) {
$usercookie = explode("_",$_COOKIE["remember_me"]);
$_SESSION[LOGIN_USER]['user_id'] = $usercookie[0];
$_SESSION[LOGIN_USER]['user_type'] = $usercookie[1];
$_SESSION[LOGIN_USER]['name'] = $usercookie[2];
$_SESSION[LOGIN_USER]['email'] = $usercookie[3];
}
So far, it seems to work, but... let's see if in some more hours the login is done automatically after I enter the website again.
EDIT 2:
Just noticed that spaces are saved into cookie as + and # as %40
EDIT 3:
FINALLY! I did it and here's what I did in order to help future users:
First, let's start by creating the cookie. I inserted a new colum in my users table to save a token, and assigned that token as an encription in MD5 to a variable, like this:
$tokenuser = md5(uniqid(rand(), true));
Once the table was updated, we must create the cookie, and here it is:
$cookie_name = "mfrm";
if($_POST['remember']=="1"){
setcookie($cookie_name, $tokenuser, time() + 31536000, '/');
}else{
setcookie($cookie_name, $tokenuser, time() + 864000, '/');
}
For those who didn't understood that "if" condition, that's simply to check if the user have selected the "checkbox" in order to be remembered "forever" (one year in this case).
So far so good, the next part was the one that was "try and error" until I finally did it! You should put this code BEFORE your headers, because otherwise it might not work and will probably give you an error:
if(isset($_COOKIE["mfrm"])) {
$usercookie = $_COOKIE["mfrm"];
}
So, this way your variable $usercookie now has the content of your cookie (the unique token we created).
"Later" on your code, you simply do a call to your database, check for which user that token is valid and then just asign user_id and all other things you want in order for user to have his login. :)
I hope whoever sees this can solve the problem, I did a LOT of Google search before I finally get this working.
My suggestion is, do a lot of "print" and "echo" in PHP so you can see where is your problem, if needed stop your code by inserting sleep(2); (where 2 means two seconds)
Good luck! :)
This won't suffice, cookies are saved in user's browser, so every time she connects, you check her cookies and and set set up her session accordingly.
Hope this helps
=== EDIT ===
This may help you: http://www.pontikis.net/blog/create-cookies-php-javascript
Let's say that the user ID is '12345', and he is logging in
You set the cookie with:
setcookie('user_id', '12345', time() + (86400 * 30), '/');
Then, then if the user logs in tomorrow, and his session has expired, you check if his user_id exists in DB from the cookies:
if(isset($_COOKIE['user_id'])) {
// check the user_id in DB and create session if exists
}else{
// User has no cookies, then he has to login
}
Hope this makes sense.
This is a very simple example, so of course, do not just put a user_id in your cookies, but a more rigorous form of authentication, like the last session id and a token you'd have generated.
=== EDIT2 ===
Is 'remember' the name of a checkbox? Because in which case, if it is not checked, $_POST['remember'] is not set. So instead of checking the value of $_POST['remember'], you should check if it is set or not
Assuming that 'remember' is the name of a checkbox:
$year = time() + 31536000;
if(isset($_POST['remember']))
{
setcookie("remember_me", $_SESSION[LOGIN_USER], $year);
}
else
{
if(isset($_COOKIE['remember_me']))
{
$tendays = time() + 864000;
setcookie("remember_me", $_SESSION[LOGIN_USER], $tendays);
}
}