简体   繁体   English

在 php 中获取请求 url 的 Content-Type

[英]Get Content-Type of requested url in php

Using php how would I be able to define the variable $type into the content-type of http://www.example.com使用 php 如何将变量$type定义为http://www.example.comcontent-type

For example: $type defined as "text/html"例如: $type定义为"text/html"

So far this is what i am working with:到目前为止,这是我正在使用的:

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

The code may be changed as much as needed可以根据需要更改代码

Have you tried:你有没有尝试过:

$type = get_headers($url, 1)["Content-Type"];

As noted in comments by @Michael, this syntax won't work without a very current version of PHP.正如@Michael 在评论中指出的那样,如果没有最新版本的 PHP,此语法将无法使用。

Have you also tried:您是否也尝试过:

$headers = get_headers($url, 1);
$type = $headers["Content-Type"];

? ?

Sometimes get_header return wrong values becouse it read http headers, but not file.有时 get_header 会返回错误的值,因为它读取的是 http 标头,而不是文件。 It should be better use finfo:最好使用 finfo:

$finfo = new finfo(FILEINFO_MIME_TYPE);
$type = $finfo->buffer(file_get_contents($link));

Not very clear on what you are trying to do, but if you are trying to get the request content type that was sent by the browser to your script, you can do this:不太清楚您要做什么,但是如果您尝试获取浏览器发送到脚本的请求内容类型,您可以这样做:

<?php 
// Collect all headers
$headers = [];
foreach(getallheaders() as $name => $header){
    $headers[strtolower($name)] = $header;
}

// Get the content type header
$contentType = $headers['content-type'];
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM