如何从类似MVC的URL中确定文件类型


How to determine file type from MVC-like URL

我想在Magento商店的产品视图页面上添加一个音频播放器来播放示例音频文件,所以我编辑了magento_root/app/design/path/to/theme/template/downloadable/catalog/product/samples.phtml

<?php if ($this->hasSamples()): ?>
 <dl class="item-options">
    <dt><?php echo $this->getSamplesTitle() ?></dt>
    <?php $_samples = $this->getSamples() ?>
    <?php foreach ($_samples as $_sample): ?>
        <dd>
            <!--HTML5 Audio player-->
            <audio controls>
                <source src="<?php echo $this->getSampleUrl($_sample) ?>" type="audio/mpeg">
                Your browser does not support the audio element.
            </audio>
            <br/>
            <a href="<?php echo $this->getSampleUrl($_sample) ?>" <?php echo $this->getIsOpenInNewWindow() ? 'onclick="this.target=''_blank''"' : ''; ?>><?php echo $this->escapeHtml($_sample->getTitle()); ?></a>
        </dd>
    <?php endforeach; ?>
  </dl>
<?php endif; ?>

这很好,但我希望播放器只显示音频文件。我的问题是$this->getSampleUrl($_sample)返回的URL的形式http://example.com/index.php/downloadable/download/sample/sample_id/1/在URL上没有关于文件类型的信息。

我考虑过获取URL的内容来确定文件类型,但我觉得仅仅为了确定文件类型而完全读取文件是愚蠢的。已尝试pathinfo(),但未返回任何有关文件类型的信息。

我想实现这样的

$sample_file = $this->getSampleUrl($_sample);
$type = getFileType($sample_file);
if(preg_match('audio-file-type-pattern',$type){ ?>
 <!--HTML5 Audio player-->
 <audio controls>
   <source src="<?php echo $sample_file ?>" type="<?php echo $type?>">
   Your browser does not support the audio element.
 </audio>
}

您可以尝试使用curl发送HEAD请求。对于HEAD请求,你只得到标题,而不是正文(在你的情况下是音频文件):

<?php
$url = 'http://domain.com/index.php/downloadable/download/sample/sample_id/1/';
$ch = curl_init();
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 20);
// Only calling the head
curl_setopt($ch, CURLOPT_HEADER, true); // header will be at output
curl_setopt($ch, CURLOPT_NOBODY, true);

$content = curl_exec ($ch);
curl_close ($ch);

echo $content;
//Outputs:
HTTP/1.1 200 OK
Date: Fri, 01 Apr 2016 16:56:42 GMT
Server: Apache/2.4.12
Last-Modified: Wed, 07 Oct 2015 18:23:27 GMT
ETag: "8d416d3-8b77a-52187d7bc49d1"
Accept-Ranges: bytes
Content-Length: 571258
Content-Type: audio/mpeg

通过一个简单的正则表达式,您可以获得文件的内容类型:

preg_match('/Content'-Type: (['w'/]+)/', $content, $m);
echo print_r($m,1);
//Outputs:
Array
(
     [0] => Content-Type: audio/mpeg
     [1] => audio/mpeg
)