2012-03-23 127 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/