Posts tagged ‘useful’

Get File Extension

Very handy PHP function to get the file extension of a file name like something.jpg

Method 1: (best way)

1
2
3
4
5
6
7
8
9
10
11
// get_file_extension ( string [the file name] , boolean [lower case] )
function get_file_extension($str,$low = true){
	$i = strrpos($str,'.');
	if (!$i)
		return '';
	$l = strlen($str) - $i;
	$ext = substr($str,$i+1,$l);
	if($low == true)
	$ext = strtolower($ext);
	return $ext;
}

Method 2:

1
2
3
4
5
6
7
8
9
10
// get_file_extension ( string [the file name] , boolean [lower case] )
function get_file_extension($str,$low = true){
	$ar = explode('.',$str);
	if(empty($ar))
		return '';
	$ar = array_reverse($ar);
	if($low == true)
	$ext = strtolower($ar[0]);
	return $ext;
}

Both functions produce the same output but one uses the string functions and the other uses array function. If you think about it, to manipulate and create arrays take more memory then manipulating regular text. (internally arrays are created using those same string manipulation methods) So method one is better because it uses most simple way to get what you need.

Make Code

Very simple handy little function to generate a random code of number and lower and upper case letters.

Straight forward stuff…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function makecode($chars = 6)
{
	for($i=0; $i<=($chars-1); $i++)
	{
		$r0 = rand(0,1);
		$r1 = rand(0,2); // frequency of lower case
		if($r0==0)
			$r .= chr(rand(ord('A'),ord('Z')));
		elseif($r0==1)
			$r .= rand(0,9);
		if($r1==0)
			$r = strtolower($r);
	}
	return $r;
}

$r0 controls if the next digit is a number or a letter
$1 controls if teh letter will be upper or lower. Set it to 0 if you want it to always be lower or change the range to what ever suits you.
Also a number maybe passed to the function to change how many digits in the code to make.