1

An IT service provider have to write our SPF changes on Internet, I just mail my instructions.

I created a program in PHP to check in one click all my domains, to see if it is correct (sometimes a bad copy-paste include bad characters)

I tried to test the SPF with

if (strpos(strtolower($spf), 'v=spf')

but this doesn't check bad characters

I tried with a preg_match but it's not working

A spf record can contain only these characters [a-z] [0-9] . ? - ~ (space) and must start with v=spf

all other characters must echo "Invalid syntax"

Example:

$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('/(v=spf)([a-z0-9-~?.])/i', $spfdata)){
    echo "SPF seems to be ok";
} else {
    echo "Invalid syntax";
}

This doesn't work it always says "ok" even if I type a bad character.

  • You did not put any quantifier after the character class - so this looks for one single character that matches the class only. And since you did not anchor your pattern to the beginning and end, _anything_ is allowed after that one character. – 04FS Oct 10 '19 at 13:55
  • 2
    There are PHP libraries to help validate SPF, such as in this question: https://stackoverflow.com/questions/36749957/how-to-validate-spf-records-with-php, why not use one instead of rolling your own? – robsiemb Oct 10 '19 at 13:56

2 Answers2

1

You may use

'/^v=spf[a-z0-9~? .-]+$/i'

Or, if you want to allow any kind of whitespace:

'/^v=spf[a-z0-9~?\s.-]+$/i'

PHP code:

$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('/^v=spf[a-z0-9~?\s.-]+$/i', $spfdata)){
    echo "SPF seems to be ok";
} else {
    echo "Invalid syntax";
}

See the PHP demo

The regex matches

  • ^ - start of string
  • v=spf - a literral text
  • [a-z0-9~?\s.-]+ - 1+ ASCII letters, digits, ~, ?, whitespaces, . or -
  • $ - end of string.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

I don't know why but when I delete the first block (v=spf) the regex seems to be good I tried a lot of differents things and finally this works (I invert the logic with the ^)

So the regex says "if your are NOT in the bracket expression you are ok"

$spfdata='v=spf1 mx 1.2.3.4 ~all';

if (preg_match('#[^a-z0-9 :\+=.\-~\?]#', $spfdata)){
    echo "Invalid syntax";
} else {
    echo "SPF seems to be ok";
}