00 Votes

PHP: Extract File Extension of a File

Question by Compi | 2015-07-07 at 18:01

I would like to extract the fileextension of an arbitrary file with the help of PHP, for example to determine the format of an upload.

Does someone know a simple PHP function for this? Reluctantly, I would like to work with the string functions such as substr, explode, implode, split or something else. There must be something simple!

ReplyPositiveNegative
0Best Answer0 Votes

Yes. There is actually a very easy way. It is called pathinfo. Let us look at a small example: 

$filename = "/www/htdocs/test.txt";

$ext = pathinfo($filename, PATHINFO_EXTENSION);

echo $ext;

Here, we are using pathinfo() for reading out the file extension of the file in $filename. As first parameter, the function is expecting the filename and as second parameter a constant depending on what you would like to read out. Possible are PATHINFO_DIRNAME, PATHINFO_BASENAME, PATHINFO_EXTENSION and PATHINFO_FILENAME.

If you omit the second parameter, an array containing all information is build. You can find an example for this in the topic about how to split a file path using PHP into its complements such as path, filename and file extension.
2015-07-07 at 18:39

ReplyPositive Negative
Reply

Related Topics

PHP: File Download Script

Tutorial | 0 Comments

Program in ZIP-Folder

Info | 0 Comments

HTACCESS: Simplify URL

Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.