PHP: Mac address validating and formatting
There are three common tasks related to storing mac address in the database as char(12) (it is feasible to use bigint instead but in our case we opted for a text type).
1. Validating mac address entered by user.
In our case user is allowed to enter mac address the way s/he wants:
000CF15698AD
00:0C:F1:56:98:AD
00-0C-F1-56-98-AD
So the perfect solution would be to apply regular expression like this one:
/([a-fA-F0-9]{2}[:|\-]?){6}/
For example, in plain PHP:
public static function IsValid($mac) { return (preg_match('/([a-fA-F0-9]{2}[:|\-]?){6}/', $mac) == 1); } |
or using Zend Framework:
public static function IsValid($mac) { $validator = new Zend_Validate_Regex('/([a-fA-F0-9]{2}[:|\-]?){6}/'); return $validator->isValid($mac); } |
2. Remove separating symbols ‘:’ or ‘-‘ from the mac address to fit only 12 character storage.
This is really easy to implement using str_replace().
public static function RemoveSeparator($mac, $separator = array(':', '-')) { return str_replace($separator, '', $mac); } |
3. Adding separating symbol ‘:’ back when the mac address is displayed to a user.
This could look a bit ugly if the straight forward solution is applied, e.g. something like below:
public static function AddSeparator($mac, $separator = ':') { $result = ''; while (strlen($mac) > 0) { $sub = substr($mac, 0, 2); $result .= $sub . $separator; $mac = substr($mac, 2, strlen($mac)); } // remove trailing colon $result = substr($result, 0, strlen($result) - 1); } |
So I kept looking for more elegant solution. Ideally I was hoping for one-line solution. And the magic comes with function str_split():
public static function AddSeparator($mac, $separator = ':') { return join($separator, str_split($mac, 2)); } |
Thanks it was really helpful : )
Love the functions, I have elaborated a bit more to make this class follow the IEEE standards and all that mumbo jumbo…
* IEEE 802 standards define 3 commonly used formats to print a MAC address in hexadecimal digits:
* Six groups of two hexadecimal digits separated by hyphens (-), like 01-23-45-67-89-ab
* Six groups of two hexadecimal digits separated by colons (:), like 01:23:45:67:89:ab
* Three groups of four hexadecimal digits separated by dots (.), like 0123.4567.89ab
public static function IsValid($mac)
{
return (preg_match(‘/([a-fA-F0-9]{2}[-:]){5}[0-9A-Fa-f]{2}|([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4}/’, $mac) == 1);
}
Thx for “adding separator” function.. It’s very elegant.
Hi,
I would like to know if PHP code could get mac address for people who open the php file,
Thank you,
Tommy
Hi Tommy,
Hope this helps http://stackoverflow.com/a/1420402!
Thanks,
Alex.
You also could try:
$res = filter_var($mac, FILTER_VALIDATE_MAC);
Returns FALSE if filter fails..