2012-03-23 115 views
0

我需要定期循環訪問我的PHP數據庫中的鏈接以檢查鏈接是否導致有效頁面。如果鏈接已過期或無效,我不想輸出它。如何檢查href值是否有效導致有效頁面?驗證鏈接href屬性

感謝任何*指針。

+1

「有效頁面」的意思是不是http狀態碼= 200? – safarov 2012-03-23 17:19:46

+0

是的,我想我會想要一個200.只是不是404或任何其他錯誤的錯誤代碼。我有一個具有特定URL的產品列表,如果供應商(如J.C. Penny等)更改它們,則這些產品的鏈接會發生變化。我不想將我的客戶發送到「舊」鏈接,因此我不想輸出這些「過期」或「無效」網址。那有意義嗎? – jrubins 2012-03-23 17:23:26

+0

你不想每次都在鏈接輸出之前這樣做......你應該用'cron'或類似的方式將它作爲一個預定的後臺任務來運行。 – prodigitalson 2012-03-23 17:29:30

回答

1

您也可以使用多個捲曲的請求每次檢查所有列表的更多更快。 Check here

0

我自己是一個noob,但我會建議使用cURL。使用快速谷歌搜索發現下面的代碼(我沒有測試):

<?php 

$statusCode = validate($_REQUEST['url']); 
if ($statusCode==’200′) 
    echo ‘Voila! URL ‘.$_REQUEST['url']. 
    ’ exists, returned code is :’.$statusCode; 
else 
    echo ‘Opps! URL ‘.$_REQUEST['url']. 
    ’ does NOT exist, returned code is :’.$statusCode; 

function validateurl($url) 
{ 
    // Initialize the handle 
    $ch = curl_init(); 
    // Set the URL to be executed 
    curl_setopt($ch, CURLOPT_URL, $url); 
    // Set the curl option to include the header in the output 
    curl_setopt($ch, CURLOPT_HEADER, true); 
    // Set the curl option NOT to output the body content 
    curl_setopt($ch, CURLOPT_NOBODY, true); 
    /* Set to TRUE to return the transfer 
    as a string of the return value of curl_exec(), 
    instead of outputting it out directly */ 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
    // Execute it 
    $data = curl_exec($ch); 
    // Finally close the handle 
    curl_close($ch); 
    /* In this case, we’re interested in 
    only the HTTP status code returned, therefore we 
    use preg_match to extract it, so in the second element 
    of the returned array is the status code */ 
    preg_match(「/HTTP\/1\.[1|0]\s(\d{3})/」,$data,$matches); 
    return $matches[1]; 
} 
?> 

來源:http://www.ajaxapp.com/2009/03/23/to-validate-if-an-url-exists-use-php-curl/