此代码有什么问题?
代码检测到用户来自预期的推荐站点并添加cookie,但在页面刷新时,代码看不到cookie并运行!isset代码并再次重新创建cookie。不知道为什么。有什么想法吗?
只是尝试确保它是正确的引用站点,然后创建cookie,以便用户可以使用整个站点,因为他们有一个cookie,现在访问权在cookie上,而不是http\\u引用者。
以下代码位于函数中。php位于子主题中,并在init hook下运行,因此它在每个页面上运行。有人告诉我这是最好的。
add_action(\'init\', \'bbb_referral_check\' );
function bbb_referral_check() {
if (!is_admin()){
$allowed_host = \'bbb.com\';
$theurl = $_SERVER[\'HTTP_REFERER\'];
//$theurl = wp_get_referrer();
$host = parse_url($theurl, PHP_URL_HOST);
$ishost = false;
if (strpos($host, $allowed_host) !== false) { $ishost = true; }
$javascript_ouput = "<script>console.log(\'Debug Info: " .$ishost. "\');
</script>";
echo $javascript_ouput;
//echo "The allowed host: ".$allowed_host; exit;
if ( !isset($_COOKIE["bbb-referral"])) {
$javascript_ouput = "<script>console.log(\'Debug Info cookie not set: \');</script>";
echo $javascript_ouput;
if ($ishost)
{
$javascript_ouput = "<script>console.log(\'Debug Info is host
match: " .$host. "\');</script>";
echo $javascript_ouput;
setcookie( "bbb-referral", "bbb-referral", time() + 1800, COOKIEPATH, COOKIE_DOMAIN);
} else {
$javascript_ouput = "<script>console.log(\'Debug Info not host match: " .$host. "\');</script>";
echo $javascript_ouput;
//Redirect
wp_redirect(\'http://bbb.com\' ); exit;
}
}//isset
$javascript_ouput = "<script>console.log(\'Debug Info cookie is set: \');</script>";
echo $javascript_ouput;
}//admin
}//function
SO网友:janh
您不能使用setcookie()
在您已经开始向主体输出内容之后(在本例中是javascript调试,但可能是该函数之外的其他内容)。
是否正在抑制PHP警告?它应该抱怨“无法发送标头;标头已发送”,并告诉您输出的开始位置。
为了解决此函数中javascript的问题,可以将脚本标记附加到变量中,并在设置cookie(或重定向)后一次性回显它们。类似这样的内容(未测试,可能包含拼写错误)。
function bbb_referral_check() {
$javascript_ouput = "";
if (!is_admin()){
$allowed_host = \'bbb.com\';
$theurl = $_SERVER[\'HTTP_REFERER\'];
//$theurl = wp_get_referrer();
$host = parse_url($theurl, PHP_URL_HOST);
$ishost = false;
if (strpos($host, $allowed_host) !== false) { $ishost = true; }
$javascript_ouput .= "<script>console.log(\'Debug Info: " .$ishost. "\');</script>";
//echo "The allowed host: ".$allowed_host; exit;
if ( !isset($_COOKIE["bbb-referral"])) {
$javascript_ouput .= "<script>console.log(\'Debug Info cookie not set: \');</script>";
if ($ishost) {
$javascript_ouput .= "<script>console.log(\'Debug Info is host match: " . $host . "\');</script>";
setcookie( "bbb-referral", "bbb-referral", time() + 1800, COOKIEPATH, COOKIE_DOMAIN);
} else {
$javascript_ouput .= "<script>console.log(\'Debug Info not host match: " .$host. "\');</script>";
//Redirect
wp_redirect(\'http://bbb.com\' ); exit;
}
}//isset
$javascript_ouput .= "<script>console.log(\'Debug Info cookie is set: \');</script>";
}//admin
echo $javascript_ouput;
}