Development Blog
April 04, 2013
Redirect return visitors to their selected choice with cookie.
My client has lander page where the visitor can select their regions and link to other websites. jQuery can be used here to create a cookie file, it will remember their selection and then redirect to the rightful place if they revisit the lander page again.
Add the PHP redirect script at the very top, ahead of everything else.
RAW 1 of 4
You can declare the click function with an ID name instead of grabbing all the A HREF tags as shown below. Now add this script to the HEAD area.
RAW 2 of 4
Add links to the BODY area.
RAW 3 of 4
This sample script is set to expire in 1 day. Understanding cookie expiration date format:
1000 * 60 = 60 seconds
(1000 * 60) * 60 = 60 minutes / 1 hour
((1000 * 60) * 60) * 24 = 24 hours / 1 Day
RESULT
Add the closing PHP script to the end of the HTML page.
RAW 2 of 4
Redirect return visitors to their selected choice with cookie.
PHP
jQuery
Cookie
My client has lander page where the visitor can select their regions and link to other websites. jQuery can be used here to create a cookie file, it will remember their selection and then redirect to the rightful place if they revisit the lander page again.
Add the PHP redirect script at the very top, ahead of everything else.
RAW 1 of 4
<?php if($_COOKIE['website_geo_opt']): header( 'Location: ' . $_COOKIE['website_geo_opt'] ); else: ?>
You can declare the click function with an ID name instead of grabbing all the A HREF tags as shown below. Now add this script to the HEAD area.
RAW 2 of 4
<script> $('a').click( function(ev){ ev.preventDefault(); url = $(this).attr('href'); setWebsiteGeoCookie( url ,1); window.location.href = url; }); function setWebsiteGeoCookie (location, expires) { var name = 'website_geo_opt'; var value = location; var domain = '.yourwebsitename.com'; var path = '/'; var now = new Date(); now.setTime( now.getTime() ); /* if the expires variable is set, update time */ if ( expires ) { expires = expires * 1000 * 60 * 60 * 24; } var expires_date = new Date( now.getTime() + (expires) ); document.cookie = name + "=" + escape( value ) + ";expires=" + expires_date.toGMTString() + ";domain=yourwebsitename.com"; } </script>
Add links to the BODY area.
RAW 3 of 4
<a href="ca.yourwebsitename.com">Canada</a><br /> <a href="cn.yourwebsitename.com">China</a><br /> <a href="uk.yourwebsitename.com">United Kingdom</a><br /> <a href="us.yourwebsitename.com">United States</a><br />
This sample script is set to expire in 1 day. Understanding cookie expiration date format:
1000 * 60 = 60 seconds
(1000 * 60) * 60 = 60 minutes / 1 hour
((1000 * 60) * 60) * 24 = 24 hours / 1 Day
RESULT
Add the closing PHP script to the end of the HTML page.
RAW 2 of 4
<?php endif; ?>