Open In App

How to get a File Extension in PHP ?

Improve
Improve
Like Article
Like
Save
Share
Report

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) {
  // strrpos() function returns the position
  // of the last occurrence of a string inside
  // another string.
  $n = strrpos($s,".");
   
  // The substr() function returns a part of a string.
  if($n===false) 
    return "";
  else
    return substr($s,$n+1);
}
     
// To Get the Current Filename.
$currentPage= $_SERVER['SCRIPT_NAME'];
 
//Function Call
echo fileExtension($currentPage);
?>


Output

php

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   
   
// To Get the Current Filename.
$path= $_SERVER['SCRIPT_NAME'];
 
// path info function is used to get info
// of The File Directory
   
// PATHINFO_FILENAME parameter in
// pathinfo() gives File Name
$name = pathinfo($path, PATHINFO_FILENAME);
   
// PATHINFO_EXTENSION parameter in pathinfo()
// gives File Extension
$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
  // This is sample url
  $url =
   
  // Here parse_url is used to return the
  // components of a URL
  $url = parse_url($url);
   
  // path info function is used to get info
  // of The File Directory
   
  // PATHINFO_FILENAME parameter in pathinfo()
  // gives File Name
  $name = pathinfo($url['path'], PATHINFO_FILENAME);
 
  // PATHINFO_EXTENSION parameter in pathinfo()
  // gives File Extension
  $ext  = pathinfo($url['path'], PATHINFO_EXTENSION);
 
  echo " Name: ", $name;
  echo "\n Extension: ", $ext;
?>


Output

 Name: file.index
 Extension: php


Last Updated : 21 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads