How to get the file extension in PHP? [duplicate]

2019-01-01 14:20发布

Possible Duplicate:
How to extract a file extension in PHP?

I wish to get the file extension of an image I am uploading, but I just get an array back.

$userfile_name = $_FILES['image']['name'];
$userfile_extn = explode(".", strtolower($_FILES['image']['name']));

Is there a way to just get the extension itself?

5条回答
皆成旧梦
2楼-- · 2019-01-01 14:32

How about

$ext = array_pop($userfile_extn);
查看更多
深知你不懂我心
3楼-- · 2019-01-01 14:39

This will work as well:

$array = explode('.', $_FILES['image']['name']);
$extension = end($array);
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-01 14:40

No need to use string functions. You can use something that's actually designed for what you want: pathinfo():

$path = $_FILES['image']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
查看更多
伤终究还是伤i
5楼-- · 2019-01-01 14:43

You could try with this for mime type

$image = getimagesize($_FILES['image']['tmp_name']);

$image['mime'] will return the mime type.

This function doesn't require GD library. You can find the documentation here.

This returns the mime type of the image.

Some people use the $_FILES["file"]["type"] but it's not reliable as been given by the browser and not by PHP.

You can use pathinfo() as ThiefMaster suggested to retrieve the image extension.

First make sure that the image is being uploaded successfully while in development before performing any operations with the image.

查看更多
柔情千种
6楼-- · 2019-01-01 14:54

A better method is using strrpos + substr (faster than explode for that) :

$userfile_name = $_FILES['image']['name'];
$userfile_extn = substr($userfile_name, strrpos($userfile_name, '.')+1);

But, to check the type of a file, using mime_content_type is a better way : http://www.php.net/manual/en/function.mime-content-type.php

查看更多
登录 后发表回答