Monday, September 21, 2009

How to Get File Extension of a file in PHP


How to determine extension of a file in php?





When you are working with files you may need to get the extension of a file. In such case you can use following methods to get the file extension.


1. Example code for get the file extension in php.

<?php

/*

©-Copyright by kottawadumi.blogspot.com

*/


$file_name='C:\myfiles\myfile.doc.jpg';

$file_extension=pathinfo ($file_name,PATHINFO_EXTENSION);

echo $file_extension;

//Extension with dot '.'

echo ".".$file_extension;

?>

This example is based on pathinfo php inbuilt method. It is the easiest way to extract the extension from a file name. By specifying PATHINFO_EXTENSION parameter, you can directly get the extension of the file otherwise it returns the associative array containing the dirname, basename, extension,and filename.

Note that above pathinfo function returns the file extension without a dot "." So you have to manually add the dot before the extension.


2. Example code for determine the extension of a file in php.

<?php

/*

©-Copyright by kottawadumi.blogspot.com

*/


function get_file_extension($file_name){

$file = strtolower($file_name);

$extension = explode(".", $file_name);

return $extension[count($extension)-1];

}

$file_name='C:\myfiles\myfile.doc.jpg';



echo get_file_extension($file_name);



?>

In this example, divide the file name using dot "." delimiter and returns the last element of the array as the file extension.


3. Example for get the extension of a file using regular expression in php.

<?php

/*

©-Copyright by kottawadumi.blogspot.com

*/


$file_name='C:\myfiles\myfile.doc.jpg';

$pattern='/(\.[^.]+)$/';

preg_match($pattern,$file_name,$matches);

echo end($matches);



?>

In this example, It uses a regular expression to extract the file extension. It returns the file extension with the dot "."













©-Copyright By Duminda Chamara  
Java Script Validation  

0 comments: