Simple snippet to get file extension in php

Following is a simple snippet I use to get a file extension in php, notice that the strrpos function returns the last position of the string “.” in filename in case there are multiple dots in file name.

  1. <?php
  2. /**
  3.  *  Function that returns file extension by its name.
  4.  *  @param unknown_type $fileName
  5.  *  @return $ext
  6.  */
  7.     function fileExt($fileName)
  8.     {
  9.         /* sttrpos to get last position of "." */
  10.         $dot = strrpos($fileName, '.');
  11.         if($dot === FALSE)
  12.             return FALSE;
  13.  
  14.         $ext = substr($fileName, $dot+1);
  15.         return $ext;
  16.     }
  17.  
  18.     $fileName = "yangqi.us.txt";
  19.     echo fileExt($fileName);
  20. ?>
<?php
/**
 *  Function that returns file extension by its name.
 *  @param unknown_type $fileName
 *  @return $ext
 */
    function fileExt($fileName)
    {
        /* sttrpos to get last position of "." */
        $dot = strrpos($fileName, '.');
        if($dot === FALSE)
            return FALSE;

        $ext = substr($fileName, $dot+1);
        return $ext;
    }

    $fileName = "yangqi.us.txt";
    echo fileExt($fileName);
?>

After doing some research, I found an easier way to utilize the php function “pathinfo()“. The function returns an array containing information about dirname, basename, extension and filename of a given path string or a filename. The sample code is as follow:

  1. <?php
  2. /**
  3.  *  Function that returns file extension by its name.
  4.  *  @param unknown_type $fileName
  5.  *  @return $ext
  6.  */
  7.     function fileExt($fileName)
  8.     {
  9.         $ext = pathinfo($fileName, PATHINFO_EXTENSION);
  10.         return $ext;
  11.     }
  12.  
  13.     $fileName = "yangqi.us.txt";
  14.     echo fileExt($fileName);
  15. ?>
<?php
/**
 *  Function that returns file extension by its name.
 *  @param unknown_type $fileName
 *  @return $ext
 */
    function fileExt($fileName)
    {
        $ext = pathinfo($fileName, PATHINFO_EXTENSION);
        return $ext;
    }

    $fileName = "yangqi.us.txt";
    echo fileExt($fileName);
?>
This entry was posted in PHP and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code lang=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" extra="">