The correct way to get the file extension in PHP

Source: Internet
Author: User

For example:

The code is as follows: Copy code

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

Or

The code is as follows: Copy code

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

The most correct method is to use the pathinfo function, for example:

The code is as follows: Copy code

Echo pathinfo ($ filename, PATHINFO_EXTENSION );

The pathinfo function supports four types of responses:

PATHINFO_DIRNAME-Directory
PATHINFO_BASENAME-file name (including extension)
PATHINFO_EXTENSION-extension
PATHINFO_FILENAME-file name (excluding the extension)

Example

The code is as follows: Copy code

Function get_extension ($ filename ){
Return pathinfo ($ filename, PATHINFO_EXTENSION );
}

Call

The code is as follows: Copy code

<? Php
Print_r (pathinfo ("/testweb/test.txt "));
?>

The following result is output:

Array (
[Dirname] =>/testweb
[Basename] => test.txt
[Extension] => txt
)

If you want to upload a file, you 'd better use the following methods.

$ Extension = $ upfile ['type']; // the file information uploaded by upload.

The code is as follows: Copy code

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.doc ument ':
$ 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 ('only Upload doc, docx, xls, pdf, and pptfile <a href = "wend. php"> re-upload </a> ');
   
   }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.