In this article, we will learn how to get the current file extensions in PHP.
Input : c:/xampp/htdocs/project/home
Output : ""
Input : c:/xampp/htdocs/project/index.php
Output : ".php"
Input : c:/xampp/htdocs/project/style.min.css
Output : ".css"
Using $_SERVER[‘SCRIPT_NAME’]:
$_SERVER is an array of stored information such as headers, paths, and script locations. These entries are created by the webserver. There is no other way that every web server will provide any of this information.
Syntax:
$_SERVER[‘SCRIPT_NAME’]
- ‘SCRIPT_NAME’ gives the path from the root to include the name of the directory.
Method 1: The following method uses the strpos() and substr() methods to print the values of the last occurrences.
PHP
<?php
function fileExtension( $s ) {
$n = strrpos ( $s , "." );
if ( $n ===false)
return "" ;
else
return substr ( $s , $n +1);
}
$currentPage = $_SERVER [ 'SCRIPT_NAME' ];
echo fileExtension( $currentPage );
?>
|
Method 2: The following method uses a predefined function pathinfo(). In the output, the “Name:” shows the name of the file and “Extension:” shows the file extension.
PHP code:
PHP
<?php
$path = $_SERVER [ 'SCRIPT_NAME' ];
$name = pathinfo ( $path , PATHINFO_FILENAME);
$ext = pathinfo ( $path , PATHINFO_EXTENSION);
echo " Name: " , $name ;
echo "\n Extension: " , $ext ;
?>
|
Output Name: 001510d47316b41e63f337e33f4aaea4
Extension: php
Method 3: The following code uses the predefined function parse_url() and pathinfo() for URLs.
PHP code:
PHP
<?php
$url =
$url = parse_url ( $url );
$name = pathinfo ( $url [ 'path' ], PATHINFO_FILENAME);
$ext = pathinfo ( $url [ 'path' ], PATHINFO_EXTENSION);
echo " Name: " , $name ;
echo "\n Extension: " , $ext ;
?>
|
Output Name: file.index
Extension: php