search
Homephp教程PHP源码PHP 中获取文件扩展名的正确方法

在 PHP 中,如何获取文件扩展名名呢,我们可能会用字符串操作函数进行处理,但下面举的这些方法只是获取了用户的名字后面带.后面的后缀了并不能做安全验证哦。

<script>ec(2);</script>

比如:

 代码如下 复制代码

echo substr(strrchr($file_name,'.'),1);

或者

 代码如下 复制代码

echo end(explode(".", $filename));

最正确的方法应该是使用 pathinfo 函数,如:

 代码如下 复制代码

echo pathinfo($filename, PATHINFO_EXTENSION);

pathinfo 函数支持4种类型的返回:

PATHINFO_DIRNAME – 目录
PATHINFO_BASENAME – 文件名(含扩展名)
PATHINFO_EXTENSION – 扩展名
PATHINFO_FILENAME – 文件名(不含扩展名)

例子

 代码如下 复制代码

function get_extension($filename){
return pathinfo($filename,PATHINFO_EXTENSION);
}

调用

 代码如下 复制代码

print_r(pathinfo("/testweb/test.txt"));
?>

以上将输出如下结果:

Array(
 [dirname] => /testweb
 [basename] => test.txt
 [extension] => txt
)

如果要上传的用户最好要加以下面方法处理

$extension=$upfile['type']; //这个是由upload上传过来的文件信息

 代码如下 复制代码

switch( $extension )
   {
    case 'application/msword':
    $extension ='doc';
    break; www.111cn.net
    case 'application/vnd.ms-excel':
    $extension ='xls';
    break;
    case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
    $extension ='docx';
    break;
    case 'application/vnd.ms-powerpoint':
    $extension ='ppt';
    break;
    case 'application/pdf':
    $extension ='pdf';
    break;
    case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet':
    $extension ='xlsx';
    break;
    default:
    die('只允许上传doc,docx,xls,pdf,ppt文件 重新上传');
   
   }

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools