Jump to content

[Answered] Php Mime_Content_Type/fileinfo


Waflix

Recommended Posts

On my website I have added this form allowing authenticated users with special permissions to upload files. However, I want to limit the types of files they can upload, and checking the file's extension isn't the most reliable method. The use of mimetypes would be a better idea, so I started with that.

 

It appeared the function 'mime_content_type' didn't work:

Fatal error: Call to undefined function mime_content_type() in /home1/waflix/public_html/test/test.php on line 2

So I hoped I could use the PECL extension recommended here, but I had no such luck:

Fatal error: Class 'finfo' not found in /home1/waflix/public_html/test/test.php on line 2

 

Even after having searched the Internet for a while, I have not been able of finding a good solution. Is there any chance this extension could be installed on the server, or do I have to wait for PHP 6 of which I've heard the extension would be installed by default?

Link to comment
Share on other sites

Hi Walfix,

 

There is an easy fix for this.

 

First, you will want to use this function:

<?php
function mime_content_type($filename, $mimePath = './') {
  $fileext = substr(strrchr($filename, '.'), 1);
  if (empty($fileext)) return (false);
  $regex = "/^([\w\+\-\.\/]+)\s+(\w+\s)*($fileext\s)/i";
  $lines = file("$mimePath/mime.types");
  foreach($lines as $line) {
  if (substr($line, 0, 1) == '#') continue; // skip comments
  $line = rtrim($line) . " ";
  if (!preg_match($regex, $line, $matches)) continue; // no match to the extension
  return ($matches[1]);
  }
  return (false); // no match at all
}
?>

 

Then, download this file to your home folder:

http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types

 

I recommend addind the following to the bottom:

application/x-httpd-php php

 

This is because by default it does not have the php extension in it,

 

Then, use the function like so:

 

 

<?php
$type = mime_content_type($filename);
?>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...