2012-03-02 132 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,如果這是所需的行爲。

相關問題