Home > Article > Backend Development > PHP function introduction—get_headers(): Get the response header information of the URL
PHP function introduction—get_headers(): Get the response header information of the URL
Overview:
In PHP development, we often need to obtain the response header information of the web page or remote resource. PHP function get_headers()
can easily obtain the response header information of the target URL and return it in the form of an array. This article will introduce the usage of the get_headers()
function and provide some related code examples.
Usage of get_headers() function: get_headers()
The function can obtain the response header of the specified URL and return it as an array. The basic syntax of the function is as follows:
array get_headers(string $url, int $format = 0)
$url
parameter represents the target URL, and $format
parameter is an optional parameter used to set the format of the returned array. By default, $format
is 0 indicating that an associative array with index and value will be returned. If $format
is set to 1, an index array is returned.
Code example:
$url = "https://www.example.com"; $headers = get_headers($url); // 打印所有的响应头信息 print_r($headers); // 打印指定的响应头信息 echo $headers[0]; // 打印第一个响应头 echo $headers[1]; // 打印第二个响应头 /* 输出示例: Array ( [0] => HTTP/1.1 200 OK [1] => Date: Thu, 19 Nov 2020 08:00:00 GMT [2] => Server: Apache/2.4.41 [3] => Content-Type: text/html; charset=UTF-8 [4] => Content-Length: 12345 ... ) */
Application scenarios: get_headers()
The application scenarios of the function in actual development are very wide. The following are some common application scenarios:
It should be noted that the get_headers()
function can generally only obtain the response header information of the HTTP protocol, and is not applicable to other protocols, such as the FTP protocol.
Summary: get_headers()
function is a very practical PHP function that can easily obtain the response header information of the target URL. Through this function, you can obtain various information of the HTTP response header, such as status code, date, server information, file size, etc. In actual development, mastering and flexibly applying the get_headers()
function can improve the usability and efficiency of the code.
Reference materials:
The above is the detailed content of PHP function introduction—get_headers(): Get the response header information of the URL. For more information, please follow other related articles on the PHP Chinese website!