开发者

Is it possible to get a file extension without knowing it?

I have a file called 94bf663a100e848fb599209af8cdc2b5.wmv. I know pathinfo will not give me the extension if I just use the name 94bf663a100e848fb599209af8cdc2b5. I believe glob is only for checking if a file exists. So is it possibl开发者_JAVA百科e to get a file extension just knowing the file name (94bf663a100e848fb599209af8cdc2b5)?


As the example on the php glob manual page suggests, glob does not simply check if the file exists, it returns every file that matches the expression.

Here's a modification of the example on that page for your needs:

$name = "94bf663a100e848fb599209af8cdc2b5";
$matching = glob($name . ".*");

$info = pathinfo($matching[0]);
$ext = $info['extension'];

This assumes there is one (and only one) file with that name (with any extension), but you should be able to modify it if the file might not exist, or there might be multiple files with the same name, and different extensions.


The finfo_file() function will inspect the byte signature of a file to return its mimetype. From there, you can mostly deduce the correct file extension.

// Adapted from the PHP docs
$finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
echo finfo_file($finfo, $filename);
finfo_close($finfo);


The first few characters of the file (binary) will usually give you some kind of hint about what the file type is.

Try it out by opening some binary files (rar, zip, mp3 etc.) in Notepad.


Try filetype() or mime_content_type() function in php... pass the file path it returns the file type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜