验证链接href属性


Validate link href attribute

我需要定期循环浏览PHP数据库中的链接,以检查链接是否指向有效页面。如果链接已过期或无效,我不想输出它。如何检查href值是否有效地指向有效页面?

谢谢你的指点。

您还可以每次使用多个CUrl请求来更快地检查所有列表。检查此处

研究旋度。它允许您在php中拉取一个站点http://www.php.net/manual/en/function.curl-exec.php然后只需检查响应上的状态代码或类似标题标签的内容。

我自己也有点傻,但我建议使用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/