avonnadozie avonnadozie - 3 years ago 120
PHP Question

How to determine file type from MVC-like URL

I want to add an audio player to product view page of a Magento store for playing sample audio files, so I edited

to this.

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

This works fine but i want the player to show only for audio files. My problem is that the URL returned by
is of the form
http://example.com/index.php/downloadable/download/sample/sample_id/1/ with no information about the file type on the URL.

I considered fetching the content of the URL to determine the file type but I feel it will be silly to completely read a file just to determine its type.
but it returns nothing about the file type.

I want to achieve something like this

$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.

Answer Source

You can try sending a HEAD request with curl. With a HEAD request you are just getting the headers and not the body (in your case the audio file):


$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;

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

With a simple regular expression you can get the file's Content-Type:

preg_match('/Content\-Type: ([\w\/]+)/', $content, $m);

echo print_r($m,1);

     [0] => Content-Type: audio/mpeg
     [1] => audio/mpeg
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download