用PHP创建规范 [英] Creating a canonical with PHP

查看:72
本文介绍了用PHP创建规范的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要PHP代码在<link />标记内生成动态的规范URL,如下所示:

I need PHP code to generate a dynamic canonical URL within the <link /> tag as follows:

<link rel="canonical" href="php goes here" />

我的网站使用PHP生成变量,如下所示:

My site uses PHP to generate variables as follows:

http://www.mysite.com/script.php?var1=blue&var2=large&pointlessvar=narrow

我希望能够返回删除&pointlessvar=narrow

然后按照我认为合适的方式重新排列变量,如下所示:

And re-arranges the variables in the manner as I see fit, like this:

<link rel="canonical" href="http://www.mysite.com/script.php?var2=large&var1=blue" />

我想这样做是出于SEO的目的,因为我的网站包含许多不同顺序的变量,这些变量为基本相同的内容提供了不同的URL(以防止SERPS中的重复并集中链接的汁液)

I want to do this for SEO purposes as my site contains many variables in different orders that give different URL'S for essentially the same content (to prevent duplication in the SERPS and to concentrate the link juice)

有人可以建议我可以在<link />标签中放置一些PHP代码吗?

Can anybody suggest some PHP code that I can place in the <link /> tag?

推荐答案

要创建规范的url,您实际上应该确保仅获得所需的参数,并将它们也固定地放置.这段代码可以做到这一点.它过滤_GET参数列表,并仅使用所需的URL来构建新的URL.我在其中添加了一些注释,以便您可以轻松调整此代码以适合您的需求.

To make a canonical url, you should actually make sure, you got only the parameters you need and put them in a fixed order too. This code does that. It filters the list of _GET paramters and build a new url with only the desired ones. I put it some comments, so you can easily adjust this code to fit your needs.

我使用array_filter,因为我不确定如果在数组上的foreach中取消设置数组元素会发生什么.

I use array_filter, because I'm not sure what happens if you unset array elements within a foreach on the array.

function params()
{
    return array('b', 'c', 'a', 'z');
}

function checkParam($a)
{
    // Checks if key $a is in array of valid parameters
    return in_array($a, params());
}

function compare($a, $b)
{
    return array_search($a, params()) - array_search($b, params());
}

function getCanonicalUrl()
{
    $querystring = '';

    // Copy and flip the array to allow filtering by key.
    $params = array_flip($_GET);

    // Filter out any params that are not wanted.
    $params = array_filter($params, 'checkParam'); 

    // If none remain, we're done.
    if (count($params) !== 0)
    {
        // Sort the rest in given order
        uasort($params, 'compare');
        // Create a query string. Mind, name and value are still flipped.
        $querystring = '?'.http_build_query(array_flip($params));
    }

    return 
        'http://'.
        // $_SERVER['HTTP_HOST'] .
        $_SERVER['SCRIPT_NAME'] .
        $querystring;
}

print getCanonicalUrl();

这篇关于用PHP创建规范的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆