在php中获取所请求URL的内容类型

Und*_*ult 3 php content-type header

使用PHP我怎么能够给变量定义$typecontent-typehttp://www.example.com

例如:$type定义为"text/html"

到目前为止,这是我正在使用的:

<?php
$url = 'http://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
Run Code Online (Sandbox Code Playgroud)

代码可以根据需要进行更改

imm*_*imm 14

你有没有尝试过:

$type = get_headers($url, 1)["Content-Type"];
Run Code Online (Sandbox Code Playgroud)

正如@Michael的评论中所指出的,如果没有最新版本的PHP,这种语法将无法运行.

你有没有试过:

$headers = get_headers($url, 1);
$type = $headers["Content-Type"];
Run Code Online (Sandbox Code Playgroud)

  • 注意,这种语法(()[])仅在PHP 5.4中有效。早期版本要求将数组保存到变量,然后检索键。 (2认同)

小智 6

有时 get_header 会返回错误的值,因为它读取的是 http 标头,而不是文件。最好使用 finfo:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->buffer(file_get_contents($link));
Run Code Online (Sandbox Code Playgroud)