Reputation: 7921
I am getting the mac of the user from the url. What I'm trying to do is match to see if the address is genuine. Cause I'll be running it against a database and I don't want to run it if it's not the right format.
This is what I have so far:
if (isset($_GET['mac'])) {
if (strlen($_GET['mac']) == 18) {
$get_mac_filtered = preg_replace('/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/', '',$_GET['mac']);
if (preg_match('/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/', $_GET['mac']) == $get_mac_filtered) {
echo 'Got a mac match! '.$get_mac_filtered;
}else {
echo 'Sorry !=';
}
}else {die();} }
I'm guessing the problem is somewhere in here (preg_match('/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/', $_GET['mac']) == $get_mac_filtered)
because it returns else
Upvotes: 1
Views: 10845
Reputation: 22756
Available since PHP 5.5, the best way to validate a MAC address is using filter_var
with the constant FILTER_VALIDATE_MAC
:
var_dump(filter_var('FA-F9-DD-B2-5E-0D', FILTER_VALIDATE_MAC));
// string(17) "FA-F9-DD-B2-5E-0D"
var_dump(filter_var('DC:BB:17:9A:CE:81', FILTER_VALIDATE_MAC));
// string(17) "DC:BB:17:9A:CE:81"
var_dump(filter_var('96-D5-9E-67-40-AB', FILTER_VALIDATE_MAC));
// string(17) "96-D5-9E-67-40-AB"
var_dump(filter_var('96-D5-9E-67-40', FILTER_VALIDATE_MAC));
// bool(false)
var_dump(filter_var('', FILTER_VALIDATE_MAC));
// bool(false)
So you can just do:
if (false === filter_var($_GET['mac'], FILTER_VALIDATE_MAC)) {
throw new \Exception('Invalid mac address');
}
Upvotes: 8
Reputation:
Remove this line. It does nothing useful:
$get_mac_filtered = preg_replace('/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/', '',$_GET['mac']);
As written, this replaces anything resembling a valid MAC address with… nothing. This is almost certainly not what you want to do here.
Instead, on the next line, compare the results of preg_match()
to 1. (It returns 1 if the regular expression matches, and 0 if it does not.)
Upvotes: 0