PDA

View Full Version : How to determine a file's extenstion, etc.



JasonDFR
02-27-2009, 10:05 AM
Every once in a while there is a question involving how to determine the characteristics of a file. I'm reading a book called Pro PHP patterns, frameworks, testing and more. And I just learned about this:



<?php

$file = '/path/to/file/file.ext';

$pathInfo = pathinfo($file);

echo 'Extension: ' . $pathInfo['extension'] . '</br />';

echo 'Base name: ' . $pathInfo['basename'] . '</br />';

echo 'Directory name: ' . $pathInfo['dirname'] . '</br />';

echo 'File name: ' . $pathInfo['filename'] . '</br />';

?>


Pretty much lies to rest any discussion on how to determine a file's extension.

Nile
02-27-2009, 01:02 PM
Or if you dont want an array, you could just do:


echo pathinfo('file.php', PATHINFO_EXTENSION);

Twey
02-27-2009, 05:13 PM
What exactly is '</br />' supposed to be?

Note that the extension of a file does not uniquely determine the contents of that file. Only the contents themselves do. For a more accurate attempt at guessing the intended interpretation of those contents, try mime_content_type (http://www.php.net/mime-content-type)() or, in PHP 5.3 or later, the Fileinfo (http://www.php.net/fileinfo) module.

JasonDFR
02-27-2009, 05:20 PM
What exactly is '</br />' supposed to be?

It's a typo. I bet you have even made a typo before. Should be <br />. And yes, I know you don't approve of XHTML.

Twey
02-27-2009, 05:57 PM
Oh, OK, I thought you copied it from the book :)

Oh, I do approve of XHTML. If I ever made a purely personal site that I could be sure wasn't going to be used as part of my portfolio, I would use XHTML in a trice. In fact, I write all my templates in XHTML, and then have them converted on the fly to HTML4 for IE (the power of Genshi (http://genshi.edgewall.org/)). For serious sites, though, most clients want to have IE support, and I hear it's considered unprofessional to throw away half your users :(

JasonDFR
02-28-2009, 08:22 AM
Intriguing. Later today or tomorrow I am going to start a thread in the HTML form to talk more about this Twey. With your method, everyone can be happy.

See ya,

J