要获取URL的信息,可以使用PHP的内置函数parse_url()和get_headers()。
parse_url()函数解析URL,返回一个关联数组,包含URL的各个部分(scheme、host、port、user、pass、path、query、fragment)。$url = 'http://www.example.com/path?param1=value1¶m2=value2#fragment';
$parts = parse_url($url);
echo 'Scheme: ' . $parts['scheme'] . '<br>';
echo 'Host: ' . $parts['host'] . '<br>';
echo 'Port: ' . $parts['port'] . '<br>';
echo 'User: ' . $parts['user'] . '<br>';
echo 'Pass: ' . $parts['pass'] . '<br>';
echo 'Path: ' . $parts['path'] . '<br>';
echo 'Query: ' . $parts['query'] . '<br>';
echo 'Fragment: ' . $parts['fragment'] . '<br>';
输出结果:
Scheme: http
Host: www.example.com
Port:
User:
Pass:
Path: /path
Query: param1=value1¶m2=value2
Fragment: fragment
get_headers()函数获取URL的响应头信息。这个函数返回一个字符串数组,包含URL的响应头的每一行。$url = 'http://www.example.com';
$headers = get_headers($url);
foreach ($headers as $header) {
echo $header . '<br>';
}
输出结果:
HTTP/1.1 200 OK
Date: Fri, 01 Jan 2022 00:00:00 GMT
Server: Apache
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
注意:get_headers()函数默认只返回响应头的第一行(状态行)和Content-Type头。如果要获取完整的响应头信息,可以设置$format参数为1。
$url = 'http://www.example.com';
$headers = get_headers($url, 1);
foreach ($headers as $key => $value) {
echo $key . ': ' . $value . '<br>';
}
输出结果:
0: HTTP/1.1 200 OK
Date: Fri, 01 Jan 2022 00:00:00 GMT
Server: Apache
Content-Type: text/html; charset=UTF-8
Content-Length: 1234
上一篇:指定php报错路径
下一篇:php身份证号
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站