Home > php教程 > php手册 > PHP判断网址是否有效的最好方法

PHP判断网址是否有效的最好方法

WBOY
Release: 2016-06-13 11:40:35
Original
823 people have browsed it

1.判断一个url能否正常访问,避免使用file_get_contents时,因为url无法访问,而出现致命错误,终止程序的问题。

$url = ‘http://www.bkjia.com’;
$ch = curl_init();
$timeout = 10;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$contents = curl_exec($ch);

if(false == $contents)
{
echo ‘Curl error: ‘ . curl_error($ch);
}
else
{
….
}

另外,可以用以下代码:

curl_getinfo($ch, CURLINFO_HTTP_CODE);

获取HTTP头文件返回的代码,如果为200,则url可正常访问,不过这个函数必须在 curl_exec() 之后使用,似乎有点多余了。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template