如何检查PHP中的数据库中是否已存在url?

时间:2012-03-02 14:48:32

标签: php

我正在检查用户提交的URL是否已存在于数据库中。我担心的是用户可以提交不同格式的相同网址。  例如网址http://mysite.com/rahul/palake/?&test=1&网址http://www.mysite.com/rahul/palake/?&test=1应该被视为同一个网址。如果我已将url存储为http://mysite.com/rahul/palake/?&test=1在我的数据库中,那么在数据库中搜索url http://www.mysite.com/rahul/palake/?&test=1应该会将消息显示为已存在的url。为此,我使用以下代码,以下代码适用于我,我想确保它涵盖所有可能的方案?或者这段代码可以即兴创作?

$url="http://dev.mysite.com/rahul/palake/?&test=1";
    $parse_url=parse_url($url);

    //first check if www is present in url or not
    if(!strstr($parse_url['host'],'www'))
    {
        $scheme=trim($parse_url['scheme']);

        //assign default scheme as http if scheme is not defined
        if( $scheme =='')
            $scheme='http';

        //create new url with 'www' embeded in it
        $url1=str_replace($scheme."://",$scheme."://www.",$url);

        //now $url1 should be like this http://www.mysite.com/rahul/palake/?&test=1 

    }

    //so that $url && $url1 should be considered as one and the same
    //i.e. mysite.com/rahul/palake/?&test=1  is equivalent to  www.mysite.com/rahul/palake/?&test=1
    //should also be equivalent to http://mysite.com/rahul/palake/?&test=1

    //code to check url already exists in database goes here

    //here I will be checking if table.url like $url or table.url like $url1
    //if record found then return msg as url already exists

2 个答案:

答案 0 :(得分:2)

www.example.org/?one=bar&two=foowww.example.org/?two=foo&one=bar怎么样?它们是相同的URI(如果已规范化)但与常规字符串比较不匹配。不同符号中相同URI的更多示例:

  • www.example.org/?one=bar&two=foowww.example.org/?one=bar&&&&two=foo
  • www.example.org/#foowww.example.org/#bar
  • www.example.org/hello/world.htmlwww.example.org/hello/mars/../world.html
  • www.example.org:80/www.example.org/
  • www.EXAMPLE.orgwww.example.org/
  • www.example.org/%68%65%6c%6c%6f.htmlwww.example.org/hello.html
  • ...

长话短说:在将URL存储到数据库之前,需要对URL进行规范化,以便以后能够对它们进行比较。

我不知道任何可以为您执行此操作的PHP库。我已经使用URI.js在javascript中实现了这一点 - 也许您可以使用它来开始......

答案 1 :(得分:1)

在某些情况下,您还必须考虑www在负载平衡环境中可以使用任意数量的子域。所以www.mysite.com可能是mysite.com或www2.mysite.com等......

我认为它本质上的网址应该是独一无二的,并且这是一个完美的scaenario,www.mysite.com和mysite.com之间的示例内容可能非常不同。

如果您使用此代码的目的是防止内容重复,那么我有两个建议可以采用更好的方法:

自动:如果您认为您的潜在匹配网址不相同,则使用curl like命令可以检索两个网址的内容并对其进行哈希以确定它们是否相同(这可能会因为很多原因而给你假阴性。)

手动:与其他内容提交系统非常相似,您可以向用户显示潜在匹配列表,并要求他们验证其内容确实是唯一的。如果您沿着这条路走下去,我会规范化数据库,以便使用唯一的ID存储每个URL,然后您可以使用该ID将其链接到您当前存储的实体。如果这是期望的行为,这将允许您有许多实体引用一个URL。