29
Jun
Quick Tip #4 - Display custom messages depending on where your visitors are coming from
Posted by Nouveller in Quick Tips
Posted by Nouveller in Quick Tips
In this quick tip, I’ll show you how to display custom messages to your visitors depending on where they click from onto your website. I saw this technique and at first thought, how is this being done?! But I’d forgot the value’s PHP can store in $_SERVER
If you want to quickly grab the code and get this up and running just copy and paste this code below into your site. This will detect people coming from Google or Twitter and display a message accordingly. If you’d like to know how it all works, read on after the snippet.
<?php // if a http refferer is set, continue // this prevents any kind of error message if it's not set if(isset($_SERVER['HTTP_REFERER'])) { // set the http refferer into the value $ref $ref = $_SERVER['HTTP_REFERER']; // if the $ref value contains 'twitter', continue if(stristr($ref, 'twitter')) { // echo the statement echo 'Welcome Twitter user'; } elseif (stristr($ref, 'google')) { // echo the statement echo 'Welcome Google user'; } } ?>
Here we open an if statement to check if the server has the HTTP referrer set, sometimes servers don’t set this value (though the majority should do) and will give you a nasty error message if they don’t, so this bit of code will prevent that from happening.
<?php if(isset($_SERVER['HTTP_REFERER'])) {
Now if the referrer is set we then store it in value of $ref for later use.
$ref = $_SERVER['HTTP_REFERER'];
Now for the important bit. I’ve now opened up another if statement that uses the function stristr to search through the HTTP referrer (remember, our HTTP referrer will be set in $ref) for the word ‘twitter’. If our statement is true, it will then say ‘Welcome Twitter user’. Though this is the most simple of uses, you could use it to display a follow message or subscribe details, whatever your noggin can think of.
if(stristr($ref, 'twitter')) { // echo the statement echo 'Welcome Twitter user'; }
That’s about it for this one, I’m thinking of maybe turning this into a plugin for WordPress using my Social Media Icons in the process, yes… no..?
My name is Benjamin Reid, I live in the UK and keep the magic locked into this site.
This entry was posted on Monday, June 29th, 2009 at 5:05 pm and is filed under Quick Tips & tagged with Google, PHP, Twitter, WordPress. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Liam Goodacre wrote on June 30, 2009
ooh nice tip
thanks,
and deff build as a WP plugin!
-Liam Goodacre