Sunday, April 29, 2012

Find Filetype of Filename in PHP

Something you may eventually want to do is to know the type of file simply by the suffix of the filename.  Functions like finfo_file and mime_ content_ type come close, but they don't actually list the filename suffix (like "txt" for "readme.txt"), and this filetype function seems to list "directory" or "file" only.

Knowing the filename suffix can be very useful, especially when managing a filesystem that has copies.  It's better to name the copy of a file as "readme(copy-1).txt" rather than "readme.txt(copy-1)", since the latter option probably isn't going to cooperate so well with your text editor/reader.  Here's a little code below that returns the suffix of a filename in a string.  It returns both the prefix and the suffix of the filename :

<?php

        // Example Filename: "Homepage.php"
        // ------------------------------------

    $file_name = "Homepage.php";

        // Filename Data
        // ------------------------------------

    $length_of_filename = strlen($file_name);
    $last_char = substr($file_name, $length_of_filename - 1, 1);

        // Parse Filename Backwards
        // ------------------------------------
   
    for($i_parse_name = 0; $i_parse_name < $length_of_filename; $i_parse_name++)
    {

            // Gather Data and Detect
            // ------------------------------------
       
        $last_char = substr($file_name, $length_of_filename - $i_parse_name + 2, 1);
       
        if($last_char == ".")
        {
            $filename_suffix = substr($file_name, $length_of_filename - $i_parse_name + 2, $i_parse_name);
            $filename_prefix = substr($file_name, 0, $length_of_filename - strlen($filename_suffix));
            $i_parse_name = $length_of_filename;
        }
    }
   
        // Print Results
        // ------------------------------------
               
    print("Filetype Results -- $filename_prefix ||| $filename_suffix");

        // Example Results:
        // ------------------------------------
        //    Filetype Results -- Homepage ||| .php

?>

Other examples:

"Best.Page.in.the.Universe.xml"
    Filetype Results -- Best.Page.in.the.Universe ||| .xml

"Best.Page.in.the.Universe.xml5789"
    Filetype Results -- Best.Page.in.the.Universe ||| .xml5789

"Home.awesome.page.php"
    Filetype Results -- Home.awesome.page ||| .php

Official Function Page: http://www.php.net/manual/en/function.filetype.php

// Note: All code appearing on the PHP Revolution blog by the blog owner is released under the Hacktivismo Enhanced-Source Software License Agreement (HESSLA), unless otherwise noted.  http://www.hacktivismo.com/about/hessla.php

No comments:

Post a Comment