File Helper for CodeIgniter

/system/application/helpers/MY_file_helper.php

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/* 
  filename without extension 
  ex: file_core_name('toto.jpg') -> 'toto'
*/
if ( ! function_exists('file_core_name'))
{
	function file_core_name($file_name)
	{
		$exploded = explode('.', $file_name);
 
		// if no extension
		if (count($exploded) == 1)
		{
			return $file_name;
		}
 
		// remove extension
		array_pop($exploded);
 
		return implode('.', $exploded);
	}
}
 
/* 
  file extension 
  ex: file_extension('toto.jpg') -> 'jpg'
*/
 
if ( ! function_exists('file_extension'))
{
	function file_extension($path)
	{
		$extension = substr(strrchr($path, '.'), 1);
		return $extension;
	}
}
 
/* 
  file size 
  ex: file_size('toto.jpg') -> '3.3 MB'
*/
if ( ! function_exists('file_size'))
{
	function file_size($path)
	{
		$num = filesize($path);
 
		// code from byte_format()
		$CI =& get_instance();
		$CI->lang->load('number');
 
		$decimals = 1;
 
		if ($num >= 1000000000000) 
		{
			$num = round($num / 1099511627776, 1);
			$unit = $CI->lang->line('terabyte_abbr');
		}
		elseif ($num >= 1000000000) 
		{
			$num = round($num / 1073741824, 1);
			$unit = $CI->lang->line('gigabyte_abbr');
		}
		elseif ($num >= 1000000) 
		{
			$num = round($num / 1048576, 1);
			$unit = $CI->lang->line('megabyte_abbr');
		}
		elseif ($num >= 1000) 
		{
			$decimals = 0; // decimals are not meaningful enough at this point
 
			$num = round($num / 1024, 1);
			$unit = $CI->lang->line('kilobyte_abbr');
		}
		else
		{
			$unit = $CI->lang->line('bytes');
			return number_format($num).' '.$unit;
		}
 
		$str = number_format($num, $decimals).' '.$unit;
 
		$str = str_replace(' ', '&nbsp;', $str);
		return $str;
	}
}
 
/* End of file MY_file_helper.php */
/* Location: ./system/application/helpers/MY_file_helper.php */

Feedback

better not use explode...

its better to use:

function file_extension($filename)
{
$path_info = pathinfo($filename);
return $path_info['extension'];
}

i use files like sound.real.mp3 or img1.logo.png
so explode wont really work..;)
just a tip to do better work..
swort
Jul 5, 2010
#1
explode is just fine.

Try this in your command line:

$ php -r '$path = "sound.real.mp3"; echo substr(strrchr($path, "."), 1).PHP_EOL;'

Output:
mp3
Oden
Sep 28, 2010
#2
Very nice indeed. Thanks for sharing.
David
Sep 19, 2012
#3