检查 url 是否存在 php
check if url exists php
我目前正在使用以下方法检查 url 是否存在
$url = 'https://www.facebook.com/a-test-example-232397848665383511';
$headers = @get_headers($url);
if(strpos($headers[0],'200')===false){
print('NOT found!');
} else {
print('found!');
}
这会打印 NOT found!
,即使该页面在访问时已清晰解析。我打印 headers 并发现它是因为它 returns 一个 302
。有没有一种方法可以执行 strpos
来测试所有可能的 header 解析值?
headers 的当前输出:
Array
(
[0] => HTTP/1.1 302 Found
[1] => Location: https://www.facebook.com/unsupportedbrowser
[2] => Vary: Accept-Encoding
[3] => Content-Type: text/html
// more array items
如果我输入我知道失败的 url,我会得到以下信息:
Array
(
[0] => HTTP/1.1 404 Not Found
[1] => P3P: CP="Facebook does not have a P3P policy."
[2] => Strict-Transport-Security: max-age=15552000; preload
// rest of array
仅针对 404 进行测试是否安全?
我会使用 cURL
进行 url 验证。示例方法如下
public function urlExists($url) {
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($httpCode >= 200 && $httpCode <= 400) {
return true;
} else {
return false;
}
}
服务器可以响应 RFC 2616 中描述的不同状态代码
对于您的任务,所有代码 2xx 和 3xx 均表示成功。
性能说明:get_headers 默认使用 GET 方法,但如果您对页面内容不感兴趣,使用 HEAD 方法会更好更快。
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = @get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status >= 200 && $status < 400 ) {
print('found!');
} else {
print('NOT found!');
}
我目前正在使用以下方法检查 url 是否存在
$url = 'https://www.facebook.com/a-test-example-232397848665383511';
$headers = @get_headers($url);
if(strpos($headers[0],'200')===false){
print('NOT found!');
} else {
print('found!');
}
这会打印 NOT found!
,即使该页面在访问时已清晰解析。我打印 headers 并发现它是因为它 returns 一个 302
。有没有一种方法可以执行 strpos
来测试所有可能的 header 解析值?
headers 的当前输出:
Array
(
[0] => HTTP/1.1 302 Found
[1] => Location: https://www.facebook.com/unsupportedbrowser
[2] => Vary: Accept-Encoding
[3] => Content-Type: text/html
// more array items
如果我输入我知道失败的 url,我会得到以下信息:
Array
(
[0] => HTTP/1.1 404 Not Found
[1] => P3P: CP="Facebook does not have a P3P policy."
[2] => Strict-Transport-Security: max-age=15552000; preload
// rest of array
仅针对 404 进行测试是否安全?
我会使用 cURL
进行 url 验证。示例方法如下
public function urlExists($url) {
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
curl_close($handle);
if($httpCode >= 200 && $httpCode <= 400) {
return true;
} else {
return false;
}
}
服务器可以响应 RFC 2616 中描述的不同状态代码 对于您的任务,所有代码 2xx 和 3xx 均表示成功。
性能说明:get_headers 默认使用 GET 方法,但如果您对页面内容不感兴趣,使用 HEAD 方法会更好更快。
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = @get_headers($url);
$status = substr($headers[0], 9, 3);
if ($status >= 200 && $status < 400 ) {
print('found!');
} else {
print('NOT found!');
}