Re: PHP to get File Type

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Tue, 2008-10-14 at 08:29 -0700, Yeti wrote:
> >   function get_file_extension($file) {
> 
> http://us2.php.net/manual/en/function.pathinfo.php
> 
> <?php
> $path_parts = pathinfo('/www/htdocs/index.html');
> 
> echo $path_parts['dirname'], "\n";
> echo $path_parts['basename'], "\n";
> echo $path_parts['extension'], "\n";
> echo $path_parts['filename'], "\n"; // since PHP 5.2.0
> ?>
> 
> Secondly the MIME type can differ from the extension (file suffix)
> It's the same with uploaded files. Although the browser sends the MIME
> type it might not be the right one, since browsers obtain the MIME by
> checking the extension.
> 
> //A yeti
> 
Different browsers return different mime-types for the same file, so you
cannot rely on that. The extension basically means squat with regards to
the mime-type, as that can be changed, so don't rely on that.

Basically, depending on what you want to achieve, there are several
things you can do. Obviously
http://br2.php.net/manual/en/function.mime-content-type.php and
http://br2.php.net/manual/en/function.finfo-file.php have already been
mentioned, but unfortunately these are not always available for every
hosting package (I'm one of the unlucky ones!)

The accepted method of detecting an image mime-type if you don't have
access to the above functions is to use the GD library to perform a
width and height calculation on the image. For other types, you can
usually determine the type based on the first few bytes in the file.
This is is simple representation of how a good operating system detects
the mime-type (Windows relies on file extensions still.) For example, if
all the characters are ascii, you could then use a bit of logic to
determine if it's an XML-based file, Windows exe files begin with MZ and
the character code 90, images usually start with a 3-letter
representation of their type, etc. You might need to do a little digging
with a hex-editor to find the file types you want, but it's generally
useful to work on a whitelist basis, i.e. only accept file types you
recognise and reject everything else.

Hope this helps!



Ash
www.ashleysheridan.co.uk


-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux