Get Content-Type of requested url in php

后端 未结 3 1814
不知归路
不知归路 2020-12-11 10:01

Using php how would I be able to define the variable $type into the content-type of http://www.example.com

For example: $type

相关标签:
3条回答
  • 2020-12-11 10:18

    Sometimes get_header return wrong values becouse it read http headers, but not file. It should be better use finfo:

    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $type = $finfo->buffer(file_get_contents($link));
    
    0 讨论(0)
  • 2020-12-11 10:31

    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'];
    ?>
    
    0 讨论(0)
  • 2020-12-11 10:32

    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.

    Have you also tried:

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

    ?

    0 讨论(0)
提交回复
热议问题