DKIM / SPF / DMARC Builder & Checker — PHP source
Build the three email-authentication DNS records — SPF, DKIM, and DMARC — as ready-to-paste TXT values, or look up a domain's live records over DNS-over-HTTPS. Import existing records, catch publishing mistakes, share via URL. Entirely client-side.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* dkim-spf-dmarc — Email authentication (SPF / DKIM / DMARC) record parsing and lookup.
*
* Language: PHP 7.4+ (standard library only — curl for the DNS-over-HTTPS
* lookup, json + base64 for the response and the DKIM key; the
* parsers themselves need nothing).
* Ported from src/lib/dkim-spf-dmarc.ts
* display source — part of CosmoDev's polyglot tool pages
*
* Two layers, mirroring the TypeScript reference:
* - Pure parsers (parseSPF / parseDKIM / parseDMARC) — deterministic, never
* throw, testable without network.
* - Check functions (checkSPF / checkDKIM / checkDMARC) — one DNS-over-HTTPS
* request to Cloudflare's public resolver, then a pure parse. No backend.
*
* Specs: SPF RFC 7208, DKIM RFC 6376, DMARC RFC 7489.
*/
declare(strict_types=1);
const DKIM_SPF_DMARC_DOMAIN_RE = '/^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/i';
const DKIM_SPF_DMARC_SELECTOR_RE = '/^[a-z0-9][a-z0-9._-]*$/i';
const DKIM_SPF_DMARC_DOH_ENDPOINT = 'https://cloudflare-dns.com/dns-query';
/**
* Strip a leading scheme, userinfo, path, query, port, and trailing dot.
*/
function dkimSpfDmarcNormalizeDomain(string $raw): string
{
$s = trim($raw);
$s = preg_replace('/^[a-z][a-z0-9+.-]*:\/\//i', '', $s) ?? $s; // scheme://
$s = preg_replace('/^mailto:/i', '', $s) ?? $s; // mailto:user@domain
if (strpos($s, '@') !== false) { // keep host of user@host
$s = substr($s, strrpos($s, '@') + 1);
}
foreach (['/', '?', ':'] as $stop) { // drop path, query, port
$pos = strpos($s, $stop);
if ($pos !== false) {
$s = substr($s, 0, $pos);
}
}
return strtolower(rtrim($s, '.'));
}
/** True when the string looks like a plausible multi-label domain. */
function dkimSpfDmarcIsDomainLike(string $domain): bool
{
return preg_match(DKIM_SPF_DMARC_DOMAIN_RE, $domain) === 1 && strlen($domain) <= 253;
}
/** True when the selector is a safe DNS label chain (no spaces, no traversal). */
function dkimSpfDmarcIsValidSelector(string $selector): bool
{
$s = trim($selector);
return $s !== '' && strlen($s) <= 100
&& preg_match(DKIM_SPF_DMARC_SELECTOR_RE, $s) === 1
&& strpos($s, '..') === false;
}
/** Strip one layer of surrounding double quotes, as TXT records carry. */
function dkimSpfDmarcUnquote(string $value): string
{
return preg_replace('/^"(.*)"$/s', '$1', $value) ?? $value;
}
/**
* Split a `k=v; k=v` tag list into a map, recording malformed terms.
* Shared by the DKIM and DMARC parsers, which use the identical grammar.
*
* @param array<string, string> $tags tag map, updated in place
* @param array<int, string> $warnings warning list, appended in place
*/
function dkimSpfDmarcParseTagList(string $txt, array &$tags, array &$warnings): void
{
foreach (explode(';', $txt) as $part) {
$term = trim(dkimSpfDmarcUnquote(trim($part)));
if ($term === '') {
continue;
}
$eq = strpos($term, '=');
if ($eq === false || $eq === 0) {
$warnings[] = "Malformed tag \"{$term}\" ignored.";
continue;
}
$tags[strtolower(trim(substr($term, 0, $eq)))] = trim(substr($term, $eq + 1));
}
}
/** Split an h=/s=/t= style colon list, or a rua=/ruf= comma list. */
function dkimSpfDmarcSplitList(?string $value, string $sep): array
{
$out = [];
foreach (explode($sep, $value ?? '') as $part) {
$part = trim($part);
if ($part !== '') {
$out[] = $part;
}
}
return $out;
}
/**
* Parse one or more (newline-joined) TXT record strings for SPF. Pure.
*
* @return array{valid: bool, version?: string, mechanisms: list<array{qualifier: string, kind: string, value?: string}>, redirect?: string, exp?: string, lookupCount: int, recordCount: int, warnings: list<string>}
*/
function dkimSpfDmarcParseSPF(string $txt): array
{
$lines = array_values(array_filter(array_map(
static fn (string $line): string => dkimSpfDmarcUnquote(trim($line)),
explode("\n", $txt)
), static fn (string $line): bool => $line !== ''));
$spfLines = array_values(array_filter($lines, static fn (string $l): bool =>
preg_match('/^v=spf1(?:\s|$)/i', $l) === 1));
$warnings = [];
if (count($spfLines) === 0) {
return ['valid' => false, 'mechanisms' => [], 'lookupCount' => 0, 'recordCount' => 0,
'warnings' => ['No v=spf1 record found in the supplied text.']];
}
if (count($spfLines) > 1) {
$warnings[] = count($spfLines) . ' SPF records found — RFC 7208 allows exactly one. '
. 'Receivers treat this as a permanent error and ignore SPF for the whole domain.';
}
$terms = preg_split('/\s+/', trim($spfLines[0])) ?: [];
$mechanisms = [];
$redirect = null;
$exp = null;
foreach (array_slice($terms, 1) as $term) {
// Modifiers use '=': redirect= and exp=
if (preg_match('/^([a-z][a-z0-9-]*)=(.*)$/i', $term, $modifier) === 1) {
$name = strtolower($modifier[1]);
if ($name === 'redirect') {
$redirect = $modifier[2];
} elseif ($name === 'exp') {
$exp = $modifier[2];
} else {
$warnings[] = "Unknown modifier \"{$term}\" ignored.";
}
continue;
}
if (preg_match('/^([+\-~?])?([a-z0-9]+)(?::(.*))?$/i', $term, $m) !== 1) {
$warnings[] = "Unrecognized term \"{$term}\" ignored.";
continue;
}
$qualifier = $m[1] ?? '+';
$kind = strtolower($m[2]);
$value = $m[3] ?? null;
if (!in_array($kind, ['all', 'include', 'a', 'mx', 'ip4', 'ip6', 'exists', 'ptr'], true)) {
$warnings[] = "Unknown mechanism \"{$term}\" ignored.";
continue;
}
if (($value === null || $value === '') && ($kind === 'include' || $kind === 'exists')) {
$warnings[] = "Mechanism \"{$term}\" is missing its required value.";
continue;
}
$mechanism = ['qualifier' => $qualifier, 'kind' => $kind];
if ($value !== null) {
$mechanism['value'] = $value;
}
$mechanisms[] = $mechanism;
}
$lookupKinds = ['include', 'a', 'mx', 'exists', 'ptr'];
$lookupCount = count(array_filter($mechanisms, static fn (array $mech): bool =>
in_array($mech['kind'], $lookupKinds, true)));
if ($redirect !== null) {
$lookupCount++;
}
$all = null;
foreach ($mechanisms as $mech) {
if ($mech['kind'] === 'all') {
$all = $mech;
break;
}
}
if ($all === null && $redirect === null) {
$warnings[] = 'No "all" mechanism and no "redirect=" — unmatched senders get a Neutral '
. 'result, so anyone can still send mail that looks like this domain.';
}
if ($all !== null && $all['qualifier'] === '+') {
$warnings[] = '"+all" explicitly allows every host on the internet to send mail as this '
. 'domain — this defeats SPF entirely.';
} elseif ($all !== null && $all['qualifier'] === '?') {
$warnings[] = '"?all" (Neutral) lets unmatched senders through with no protection. Prefer "~all" or "-all".';
}
if (count(array_filter($mechanisms, static fn (array $mech): bool => $mech['kind'] === 'ptr')) > 0) {
$warnings[] = 'The "ptr" mechanism is deprecated (RFC 7208 §5.5) and should not be used.';
}
if ($redirect !== null && $all !== null) {
$warnings[] = 'A "redirect=" modifier is ignored when an "all" mechanism is present.';
}
if ($lookupCount > 10) {
$warnings[] = "{$lookupCount} DNS-lookup mechanisms — RFC 7208 §4.6.4 caps SPF at 10. "
. 'Receivers that hit the cap return permerror and ignore the record.';
}
$record = ['valid' => true, 'version' => $terms[0], 'mechanisms' => $mechanisms,
'lookupCount' => $lookupCount, 'recordCount' => count($spfLines), 'warnings' => $warnings];
if ($redirect !== null) {
$record['redirect'] = $redirect;
}
if ($exp !== null) {
$record['exp'] = $exp;
}
return $record;
}
/**
* Decode base64 without raising on bad input. Missing padding is added first;
* the DKIM p= tag is frequently published unpadded. Returns null on failure.
*/
function dkimSpfDmarcDecodeBase64Lenient(string $b64): ?string
{
$clean = preg_replace('/\s+/', '', $b64) ?? '';
$padded = $clean . str_repeat('=', (4 - strlen($clean) % 4) % 4);
$decoded = base64_decode($padded, true);
return $decoded === false ? null : $decoded;
}
/**
* Parse a `<selector>._domainkey` TXT record. Pure.
*
* @return array{valid: bool, version?: string, keyType: string, publicKey?: string, keyBits?: int, hashes: list<string>, services: list<string>, flags: list<string>, warnings: list<string>}
*/
function dkimSpfDmarcParseDKIM(string $txt): array
{
$warnings = [];
$tags = [];
dkimSpfDmarcParseTagList($txt, $tags, $warnings);
$version = $tags['v'] ?? null;
if ($version !== null && strtoupper($version) !== 'DKIM1') {
$warnings[] = "Unusual version tag v={$version} (expected DKIM1).";
}
$keyType = $tags['k'] ?? 'rsa';
$p = $tags['p'] ?? null;
$hashes = dkimSpfDmarcSplitList($tags['h'] ?? null, ':');
$services = dkimSpfDmarcSplitList($tags['s'] ?? null, ':');
$flags = dkimSpfDmarcSplitList($tags['t'] ?? null, ':');
$record = ['valid' => true, 'keyType' => $keyType, 'hashes' => $hashes,
'services' => $services, 'flags' => $flags, 'warnings' => $warnings];
if ($version !== null) {
$record['version'] = strtoupper($version);
}
if ($p === null) {
$record['valid'] = false;
$record['warnings'][] = 'No p= tag — this record is not a usable DKIM key.';
return $record;
}
if ($p === '') {
$record['warnings'][] = 'p= is empty — the key is revoked. Receivers will treat mail '
. 'signed with this selector as unsigned.';
return $record;
}
$decoded = dkimSpfDmarcDecodeBase64Lenient($p);
if ($decoded === null) {
$record['warnings'][] = 'The p= value is not valid base64 — the key could not be read.';
return $record;
}
$record['publicKey'] = preg_replace('/\s+/', '', $p) ?? $p;
if ($keyType === 'rsa') {
// SubjectPublicKeyInfo DER ≈ modulus bits/8 + ~24 bytes of ASN.1 overhead.
$bits = max(0, strlen($decoded) - 24) * 8;
$record['keyBits'] = $bits;
if ($bits < 1024) {
$record['warnings'][] = "Weak RSA key (~{$bits} bits). Keys under 1024 bits are "
. 'considered breakable; RFC 8301 discourages short keys.';
} elseif ($bits < 2048) {
$record['warnings'][] = "RSA key of ~{$bits} bits works today but is below the "
. 'recommended 2048 bits (RFC 8301).';
}
}
if (in_array('y', $flags, true)) {
$record['warnings'][] = 't=y — the key is in test mode: receivers must treat signatures as if unsigned.';
}
if (in_array('s', $flags, true)) {
$record['warnings'][] = 't=s — strict domain matching: the key cannot be used for '
. 'subdomain signatures (informational).';
}
return $record;
}
/**
* Parse a `_dmarc` TXT record. Pure.
*
* @return array{valid: bool, policy?: string, subdomainPolicy?: string, aggregateUris: list<string>, forensicUris: list<string>, percent?: int, dkimAlignment?: string, spfAlignment?: string, warnings: list<string>}
*/
function dkimSpfDmarcParseDMARC(string $txt): array
{
$warnings = [];
$tags = [];
dkimSpfDmarcParseTagList($txt, $tags, $warnings);
$record = ['valid' => true, 'aggregateUris' => [], 'forensicUris' => [], 'warnings' => &$warnings];
$version = $tags['v'] ?? null;
if ($version === null || $version === '') {
$record['valid'] = false;
$warnings[] = 'No v= tag — this is not a DMARC record.';
unset($record['warnings']);
$record['warnings'] = $warnings;
return $record;
}
if (strtoupper($version) !== 'DMARC1') {
$record['valid'] = false;
$warnings[] = "Unknown version v={$version} (expected DMARC1).";
unset($record['warnings']);
$record['warnings'] = $warnings;
return $record;
}
$policies = ['none', 'quarantine', 'reject'];
$p = strtolower($tags['p'] ?? '');
if ($p === '') {
$record['valid'] = false;
$warnings[] = 'No p= policy tag — DMARC requires it.';
unset($record['warnings']);
$record['warnings'] = $warnings;
return $record;
}
if (!in_array($p, $policies, true)) {
$record['valid'] = false;
$warnings[] = "Invalid policy p={$p} (expected none, quarantine, or reject).";
unset($record['warnings']);
$record['warnings'] = $warnings;
return $record;
}
$record['policy'] = $p;
$sp = strtolower($tags['sp'] ?? '');
if ($sp !== '') {
if (in_array($sp, $policies, true)) {
$record['subdomainPolicy'] = $sp;
} else {
$warnings[] = "Invalid sp={$sp} ignored (expected none, quarantine, or reject).";
}
}
$record['aggregateUris'] = dkimSpfDmarcSplitList($tags['rua'] ?? null, ',');
$record['forensicUris'] = dkimSpfDmarcSplitList($tags['ruf'] ?? null, ',');
if (array_key_exists('pct', $tags)) {
$pct = $tags['pct'];
if (preg_match('/^\d+$/', $pct) === 1 && (int) $pct <= 100) {
$record['percent'] = (int) $pct;
} else {
$warnings[] = "Invalid pct={$pct} ignored (must be 0-100).";
}
}
foreach (['adkim' => 'dkimAlignment', 'aspf' => 'spfAlignment'] as $tag => $key) {
$value = $tags[$tag] ?? null;
if ($value !== null && $value !== '') {
if ($value === 'r' || $value === 's') {
$record[$key] = $value;
} else {
$warnings[] = "Invalid {$tag}={$value} ignored (expected r or s).";
}
}
}
if ($record['policy'] === 'none') {
$warnings[] = 'p=none is monitor-only — no mail is quarantined or rejected, but you '
. 'still need SPF/DKIM to pass for reports to be useful.';
}
if (count($record['aggregateUris']) === 0) {
$warnings[] = 'No rua= address — without aggregate reports you cannot see who is failing '
. 'authentication. Add rua=mailto:reports@example.com.';
} elseif (count($record['forensicUris']) > 0) {
$warnings[] = 'ruf= (forensic reports) is supported by few receivers and may leak message '
. 'content to the report address (informational).';
}
$percent = $record['percent'] ?? null;
if ($percent !== null && $percent < 100 && $record['policy'] !== 'none') {
$warnings[] = "pct={$percent} applies the policy to only {$percent}% of mail — the other "
. (100 - $percent) . '% is unaffected.';
}
$record['warnings'] = $warnings;
return $record;
}
/**
* Query TXT records for a name via Cloudflare's DoH JSON API. Returns
* unquoted strings. Throws RuntimeException on transport / resolver errors.
*
* @return list<string>
*/
function dkimSpfDmarcQueryTxt(string $name): array
{
$url = DKIM_SPF_DMARC_DOH_ENDPOINT . '?name=' . rawurlencode($name) . '&type=TXT';
$ch = curl_init($url);
if ($ch === false) {
throw new RuntimeException('DNS lookup failed.');
}
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTPHEADER => ['Accept: application/dns-json'],
]);
$body = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
$error = curl_error($ch);
curl_close($ch);
if ($body === false) {
throw new RuntimeException($error !== '' ? $error : 'DNS lookup failed.');
}
if ($status !== 200) {
throw new RuntimeException("DNS resolver responded with HTTP {$status}.");
}
$json = json_decode((string) $body, true);
if (!is_array($json)) {
throw new RuntimeException('DNS resolver returned a malformed response.');
}
if (($json['Status'] ?? -1) === 3) {
return []; // NXDOMAIN — no such domain
}
if (($json['Status'] ?? -1) !== 0) {
throw new RuntimeException('DNS query failed with status ' . ($json['Status'] ?? -1) . '.');
}
$answers = is_array($json['Answer'] ?? null) ? $json['Answer'] : [];
$out = [];
foreach ($answers as $answer) {
if (($answer['type'] ?? null) === 16) {
// multi-chunk TXT arrives as "part1" "part2"
$out[] = str_replace('" "', '', dkimSpfDmarcUnquote((string) ($answer['data'] ?? '')));
}
}
return $out;
}
/** @return array{status: string, found: bool, record?: array, message?: string} */
function dkimSpfDmarcFail(string $message): array
{
return ['status' => 'fail', 'found' => false, 'message' => $message];
}
/** Look up and evaluate a domain's SPF record. */
function dkimSpfDmarcCheckSPF(string $domain): array
{
$host = dkimSpfDmarcNormalizeDomain($domain);
if (!dkimSpfDmarcIsDomainLike($host)) {
return dkimSpfDmarcFail('Enter a valid domain, e.g. example.com.');
}
try {
$record = dkimSpfDmarcParseSPF(implode("\n", dkimSpfDmarcQueryTxt($host)));
} catch (RuntimeException $e) {
return dkimSpfDmarcFail($e->getMessage());
}
if (!$record['valid']) {
return dkimSpfDmarcFail("No SPF record found for {$host}. Receivers cannot verify which "
. 'servers may send mail for it.');
}
$status = count($record['warnings']) > 0 ? 'warn' : 'pass';
$result = ['status' => $status, 'found' => true, 'record' => $record];
if ($status === 'pass') {
$result['message'] = 'SPF record found and looks healthy.';
}
return $result;
}
/** Look up and evaluate a domain's DKIM public key for one selector. */
function dkimSpfDmarcCheckDKIM(string $domain, string $selector): array
{
$host = dkimSpfDmarcNormalizeDomain($domain);
if (!dkimSpfDmarcIsDomainLike($host)) {
return dkimSpfDmarcFail('Enter a valid domain, e.g. example.com.');
}
$sel = strtolower(trim($selector));
if (!dkimSpfDmarcIsValidSelector($sel)) {
return dkimSpfDmarcFail('Enter a valid selector (letters, digits, dots, hyphens, underscores).');
}
try {
$record = dkimSpfDmarcParseDKIM(implode("\n", dkimSpfDmarcQueryTxt("{$sel}._domainkey.{$host}")));
} catch (RuntimeException $e) {
return dkimSpfDmarcFail($e->getMessage());
}
if (!$record['valid']) {
return dkimSpfDmarcFail("No DKIM record found at {$sel}._domainkey.{$host}. Try another "
. 'selector — only one is checked per lookup.');
}
$revoked = count(array_filter($record['warnings'], static fn (string $w): bool =>
strpos($w, 'revoked') !== false)) > 0;
$status = $revoked ? 'fail' : (count($record['warnings']) > 0 ? 'warn' : 'pass');
return ['status' => $status, 'found' => true, 'record' => $record];
}
/** Look up and evaluate a domain's DMARC policy. */
function dkimSpfDmarcCheckDMARC(string $domain): array
{
$host = dkimSpfDmarcNormalizeDomain($domain);
if (!dkimSpfDmarcIsDomainLike($host)) {
return dkimSpfDmarcFail('Enter a valid domain, e.g. example.com.');
}
try {
$record = dkimSpfDmarcParseDMARC(implode("\n", dkimSpfDmarcQueryTxt("_dmarc.{$host}")));
} catch (RuntimeException $e) {
return dkimSpfDmarcFail($e->getMessage());
}
if (!$record['valid']) {
return dkimSpfDmarcFail("No DMARC record found at _dmarc.{$host}. Receivers have no "
. 'policy to apply when SPF or DKIM fails.');
}
$status = count($record['warnings']) > 0 ? 'warn' : 'pass';
return ['status' => $status, 'found' => true, 'record' => $record];
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →