in PHP Snippets

Display Different Content For Visitors From Twitter


For website marketing reasons you might want to see how a visitor is finding your site so you can display a different message for different users. This can be helpful for users who have submitted this link on twitter and clicked through to your site. If you know that the visitor came from twitter, you know they are active on twitter. If you know a visitor is active on twitter you might be want to just encourage them to retweet this page, by displaying a custom message for only twitter users. You can then expand on this idea and visitors coming from facebook will have a like button, visitors from stumbleupon will have a stumble button, visitors from Google+ you can display a +1 button and so on. To get the page the visitor came from we need to access the the PHP Server variable.


The server variable stores lots of variables about the current server, the variable we are interested in is the HTTP_REFERER variable. This stores the page the visitor came from to get onto this page, this is what analytic reports will look for to let you know how visitors are coming to your site. So if we can access this variable we can then work out how the visitor came to your site.

How To Know The Visitor Arrived From Twitter

So we know how to get the last page the visitor was on so we can work out the website they were on to find your site. If a visitors clicks on your link on twitter they will come to your site with a HTTP_REFERER value of Now all you have to do is search the HTTP_REFERER variable for the string, then if it exists you can display a message just for the twitter users.

Search PHP String

To search for the string inside a variable you need to use the PHP function strpos(). This will search for the and return the position which it is found. The below snippet will search the HTTP_REFERER variable to find

if (strpos("",$_SERVER[HTTP_REFERER]) !== false) {  
     echo "Hello Twitter visitor! Hope you enjoy the post please retweet it to all your followers.";  

Or to find users from facebook.

if (strpos("",$_SERVER[HTTP_REFERER]) !== false) {  
     echo "Hello Facebook visitor! Hope you enjoy the post please like this post to all your friends.";  

Subscribe To The Weekly Newsletter

Get weekly updates to your email