检查PHP中是否存在URL的最佳方法是什么? [英] What is the best way to check if a URL exists in PHP?

查看:85
本文介绍了检查PHP中是否存在URL的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看URL是否存在且响应不是404的最佳方法是什么?

What is the best way to see a URL exists and the response is not a 404 ?

推荐答案

您可以使用get_headers($url)

手册中的示例2:

<?php
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
    array(
        'http' => array(
            'method' => 'HEAD'
        )
    )
);
print_r(get_headers('http://example.com'));

// gives
Array
(
    [0] => HTTP/1.1 200 OK 
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix)  (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

第一个数组元素将包含HTTP响应状态代码.您必须对此进行解析.

The first array element will contain the HTTP Response Status code. You have to parse that.

请注意,示例中的get_headers函数将发出HTTP HEAD请求,这意味着它不会获取URL的正文.这比使用GET请求(该请求也将返回正文)更为有效.

Note that the get_headers function in the example will issue an HTTP HEAD request, which means it will not fetch the body of the URL. This is more efficient than using a GET request which will also return the body.

还要注意,通过设置 default 上下文,任何使用http流上下文的后续调用现在都将发出HEAD请求.因此,请确保将默认上下文重置为在完成后再次使用GET.

Also note that by setting a default context, any subsequent calls using an http stream context, will now issue HEAD requests. So make sure to reset the default context to use GET again when done.

PHP还提供了变量$ http_response_header

$http_response_header数组与get_headers()函数相似.使用 HTTP包装器时,$http_response_header将填充HTTP响应标头. $http_response_header将在本地范围内创建.

The $http_response_header array is similar to the get_headers() function. When using the HTTP wrapper, $http_response_header will be populated with the HTTP response headers. $http_response_header will be created in the local scope.

如果要下载远程资源的内容,则不希望执行两个请求(一个请求用于查看资源是否存在,另一个请求用于获取资源),而不仅仅是一个.在这种情况下,请使用file_get_contents之类的内容来获取内容,然后检查变量中的标头.

If you want to download the content of a remote resource, you don't want to do two requests (one to see if the resource exists and one to fetch it), but just one. In that case, use something like file_get_contents to fetch the content and then inspect the headers from the variable.

这篇关于检查PHP中是否存在URL的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆