Using PHP $_SERVER[HTTP_REFERER] to display custom welcome messages/content

I’m trying to display a custom welcome message to visitors based off what social media site they are coming in from. I can’t get this string to work but it is echoing back no matter what the refering site is. Can anyone help me get this to work? Many thanks!

<?php 
if (strpos("twitter.com",$_SERVER[HTTP_REFERER])==0) {
    echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers"; 
} 
?>

Tried using

Read More
<?php 
if(isset($_SERVER['HTTP_REFERER'])) {
    echo $_SERVER['HTTP_REFERER'];
}
?>

to get this to work but no luck.

Related posts

Leave a Reply

2 comments

  1. strpos returns false when the search word does not appear in the string. 0 also evaluates to false when compared to a boolean. So false == 0, and your code always runs.

    Use a strict comparison to require both value and type match instead of ==

    if (strpos("twitter.com", $_SERVER['HTTP_REFERER']) === 0) {
        echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers";
    }
    

    However, the referrer will not start with twitter.com, it’ll start with http:// or https:// so your condition wasn’t right in the first place. To search for twitter.com anywhere else in the string:

    if (strpos("twitter.com", $_SERVER['HTTP_REFERER']) !== false) {
        echo "Welcome, Twitter User! If you enjoy this post, don't hesitate to retweet it to your followers";
    }
    
  2. I think you may have confused strpos() with strcmp(), being strcmp() returns 0 when two strings are equal. strpos() returns the position at which a string was found. Try:

    <?php
    if (strpos('twitter.com', $_SERVER['HTTP_REFERER'] != 0)) {
        echo "Welcome, twitter user.";
    }
    ?>