PHP查找当前URL文件扩展名
1 <html>2 <body>
3 <?php
4 $paths[] = $_SERVER['REQUEST_URI']; //$_SERVER['REQUEST_URI']获取当前请求URI,不包括域名
5 $paths[] = $_SERVER['SCRIPT_NAME']; //$_SERVER['SCRIPT_NAME']获取当前执行脚本的名称,该路径从document_root开始
6 $paths[] = $_SERVER['SCRIPT_FILENAME']; //$_SERVER['SCRIPT_FILENAME']当前执行脚本的绝对路径名
7 $paths[] = $_SERVER['PHP_SELF']; //$_SERVER['PHP_SELF']获取当前正在执行脚本的文件名,路径从document_root开始,与$_SERVER['SCRIPT_NAME']不同在于如果使用php-cgi执行脚本,则$_SERVER['SCRIPT_NAME']显示的是php-cgi,而$_SERVER['PHP_SELF']显示的是脚本文件,如:index.php
8 $paths[] = __FILE__; //获取文件的完整绝对路径和文件名
9
10 foreach($paths as $path) {
11 $file_names[] = basename($path); //获取路径中的文件名部分,皆为index.php,下面程序使用$file_names;
12 }
13
14 #第一种方法,使用explode
15 $arr = explode('.', $file_names);
16 $extend_names[] = end($arr);
17
18 #第二种方法,使用strpos和substr
19 $extend_names[] = substr($file_names, strpos($file_names, '.') + 1);
20
21 #第三种方法,使用正则表达式
22 $pattern = '/.+\.(.+)/';
23 preg_match($pattern, $file_names, $matches);
24 $extend_names[] = end($matches);
25
26 var_dump($paths);
27 echo '<br>';
28 var_dump($file_names);
29 echo '<br>';
30 var_dump($extend_names);
31 echo '<br>';
32 ?>
33 </body>
34 </html>
访问URL为: www.local.com/sub/index.php
页面输出
array(5) { => string(14) "/sub/index.php" => string(14) "/sub/index.php" => string(20) "D:/www/sub/index.php" => string(14) "/sub/index.php" => string(20) "D:\www\sub\index.php" }
array(5) { => string(9) "index.php" => string(9) "index.php" => string(9) "index.php" => string(9) "index.php" => string(9) "index.php" }
array(3) { => string(3) "php" => string(3) "php" => string(3) "php" }
页:
[1]