When uploading php files, we need to obtain the file name suffix and then determine the simple file type. In php, the file name suffix acquisition method is very simple and there are many methods. I will summarize them below.
1. basename ()-returned path file name
See the following php code:
The Code is as follows: |
Copy code |
<? Php $ Path = "/usr/www/html/index. php "; Echo basename ($ path). "<br> "; // If suffix is selected, the extension is ignored. Echo basename ($ path, ". php "); ?> |
Running result:
Index. php
Index
2. dirname ()-returns the file path of the current script!
Php code:
The Code is as follows: |
Copy code |
<? Php // -- FILE _ returns the complete FILE path $ Dir = dirname (_ FILE __); Echo $ dir; ?>
|
Running result:
F: webzendexercise
3. pathinfo () returns an associated array containing path information.
It includes the following array units: path name dirname, file name basename, and extension name extension.
See the following simple code Demonstration:
The Code is as follows: |
Copy code |
<? Php $ Path = "/usr/www/html/index. php "; $ Pathinfo = pathinfo ($ path ); Echo "directory name: $ pathinfo [dirname] <br> "; Echo "File Name: $ pathinfo [basename] <br> "; Echo "extension: $ pathinfo [extension]"; ?> |
Running result:
Directory Name:/usr/www/html
File Name: index. php
Extension: php
4. realpath -- returns the normalized absolute path name.
The php code is as follows:
The Code is as follows: |
Copy code |
<? Php $ Path = "./exercise/php.txt "; $ Realpath = realpath ($ path ); Echo $ realpath; ?>
|
Note one tips: the file path operators in different paths may be different. In windows, you can use "/" and "",
Only "/" can be used in linux, so we recommend that you use "/" during development, such as the file path above!
<? Php
// Method 1:
The Code is as follows: |
Copy code |
Function extend_1 ($ file_name) { $ Retval = ""; $ Pt = strrpos ($ file_name, "."); If ($ pt) $ retval = substr ($ file_name, $ pt + 1, strlen ($ file_name)-$ pt ); Return ($ retval ); } |
// Method 2
Php code
The Code is as follows: |
Copy code |
Function extend_2 ($ file_name) { $ Extend = pathinfo ($ file_name ); $ Extend = strtolower ($ extend ["extension"]); Return $ extend; } |
// Method 3
Php code
The Code is as follows: |
Copy code |
Function extend_3 ($ file_name) { $ Extend = explode (".", $ file_name ); $ Va = count ($ extend)-1; Return $ extend [$ va]; } |
// Method 4
Php code
The Code is as follows: |
Copy code |
Function getFileExt ($ file_name) { While ($ dot = strpos ($ file_name, ".") { $ File_name = substr ($ file_name, $ dot + 1 ); } Return $ file_name; }
|
?>