检查链接是否在php中损坏 [英] Check if links are broken in php
问题描述
我想知道是否有任何好的PHP脚本(库)来检查链接是否断开?我有一个指向mysql表中文档的链接,并且可能只是检查该链接是否指向该文档,或者是否将我重定向到了另一个URL.任何的想法?我更喜欢用PHP来做.
I wonder if there is any good PHP script (libraries) to check if link are broken? I have links to documents in a mysql table and could possibly just check if the link leads to a the document, or if I am redirected to anther url. Any idea? I would prefer to do it in PHP.
可能与以下内容有关: 检查链接是否有效,如果不能从视觉上将其标识为坏了
Might be related to: Check link works and if not visually identify it as broken
推荐答案
您可以使用以下功能检查链接是否断开:
You can check for broken link using this function:
function check_url($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch , CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$headers = curl_getinfo($ch);
curl_close($ch);
return $headers['http_code'];
}
您需要安装CURL
才能正常工作.现在,您可以使用以下方法检查断开的链接:
You need to have CURL
installed for this to work. Now you can check for broken links using:
$check_url_status = check_url($url);
if ($check_url_status == '200')
echo "Link Works";
else
echo "Broken Link";
也请检查此链接以获取HTTP状态代码: HTTP状态代码
Also check this link for HTTP status codes : HTTP Status Codes
我想您也可以检查301
和302
状态代码.
I think you can also check for 301
and 302
status codes.
另外一种方法是使用get_headers
函数.但这仅在您的PHP版本大于5时有效:
Also another method would be to use get_headers
function . But this works only if your PHP version is greater than 5 :
function check_url($url) {
$headers = @get_headers( $url);
$headers = (is_array($headers)) ? implode( "\n ", $headers) : $headers;
return (bool)preg_match('#^HTTP/.*\s+[(200|301|302)]+\s#i', $headers);
}
在这种情况下,只需检查输出:
In this case just check the output :
if (check_url($url))
echo "Link Works";
else
echo "Broken Link";
希望这对您有帮助:).
Hope this helps you :).
这篇关于检查链接是否在php中损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!