2012-03-02 188 views
1

我有一个情况,我正在检查用户提交的URL是否已经存在于数据库中。我关心的是用户可以以不同的格式提交相同的网址。 例如URL http://mysite.com/rahul/palake/?&test=1 & URL 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已经存在。为此,我使用以下代码,下面的代码适用于我,我想确保它涵盖所有可能的场景?或者这个代码可以即兴创作?如何检查PHP数据库中是否已经存在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 
+5

一般来说,不能保证“www.somesite.com”和“somesite。com“是相当的,顺便说一下... – Dmitri 2012-03-02 14:52:32

回答

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。

我不知道任何PHP库会为你做这个。我已经在JavaScript中使用了URI.js - 也许你可以使用它来开始...

+0

谢谢...我会尝试一下URI.js – Rahul 2012-03-02 15:17:44

1

你还必须考虑一个事实,www在某些情况下可能是在负载平衡环境中的任何数量的子域。所以www.mysite.com可能是mysite.com或www2.mysite.com等...

我相信一个网址,它的本质应该是独一无二的,这是一个完美的scaenario,示例内容可能会非常不同www.mysite.com和mysite.com。

如果这个代码的目的是防止重复内容,然后我有一个更好的方法有两个建议:

自动:如果你认为你有潜在的匹配URL,它是不相同的,则通过使用像命令一样卷曲,你可以检索这两个URL的内容并对它们进行哈希以确定它们是否相同(由于许多原因,这可能会给你带来错误的否定)。

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

相关问题