PHP Mac Address Validation and Formatting

I have been working on a small php app to perform a network scan and fill a database with the discovered information. The issue is that, depending on what you perform the scan with, the MAC addresses are in a number of different formats. This PHP functions validates a MAC and returns false if its not valid or a variety of formats depending on your needs! If anyone has any thoughts on improving this function feel free to let me know and I will post the updates.

 
function format_mac($mac, $format='linux'){
 
	$mac = preg_replace("/[^a-fA-F0-9]/",'',$mac);
 
	$mac = (str_split($mac,2));
	if(!(count($mac) == 6))
		return false;
 
	if($format == 'linux' || $format == ':'){
		return $mac[0]. ":" . $mac[1] . ":" . $mac[2]. ":" . $mac[3] . ":" . $mac[4]. ":" . $mac[5];
	}elseif($format == 'windows' || $format == '-'){
		return $mac[0]. "-" . $mac[1] . "-" . $mac[2]. "-" . $mac[3] . "-" . $mac[4]. "-" . $mac[5];
	}elseif($format == 'cisco'){
		return $mac[0] . $mac[1] . ":" . $mac[2] . $mac[3] . ":" . $mac[4] . $mac[5];
	}else{
		return $mac[0]. "$format" . $mac[1] . "$format" . $mac[2]. "$format" . $mac[3] . "$format" . $mac[4]. "$format" . $mac[5];
	}
}
 
//some usage examples
$rmac = "00:12:23:56:78:90";
 
echo format_mac($rmac,'cisco');
//0012:2356:7890
 
echo format_mac($rmac,'-');
//00-12-23-56-78-90
 
echo format_mac($rmac,'linux');
//00:12:23:56:78:90
 
echo format_mac($rmac,'?');
//00?12?23?56?78?90
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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.