Using PHP $_SERVER[HTTP_REFERER] to display custom

2019-07-17 16:37发布

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

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

to get this to work but no luck.

标签: php wordpress
2条回答
做自己的国王
2楼-- · 2019-07-17 16:52

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.";
}
?>
查看更多
聊天终结者
3楼-- · 2019-07-17 17:05

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";
}
查看更多
登录 后发表回答