Email Header Analyzer — PHP source
Paste raw email headers to trace the message path, detect spoofing, and check SPF/DKIM/DMARC authentication results. Runs entirely in your browser.
This is the PHP implementation — the same logic the interactive tool runs, in a shareable, citable form.
<?php
/**
* email-header-analyzer — RFC 5322 header parser + spoofing / authentication analysis.
*
* Language: PHP 7.4+ (standard library only).
* CosmoDev polyglot showcase port of the `email-header-analyzer` tool, ported
* from src/lib/email-header-analyzer.ts (the canonical TypeScript implementation).
*
* Pure string parsing — no Composer packages, deterministic. Dates go through
* date_create_immutable() (PHP's native lenient parser, RFC 2822 included) in
* place of the TS Date.parse; PCRE drives the same extraction regexes.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
declare(strict_types=1);
const EHA_SUSPICIOUS_MAILERS = ['bulk', 'mass mail', 'massmail', 'storm', 'flood', 'bomber', 'grabber', 'harvest', 'spambot', 'stealth', 'anonymous', 'dark', 'crack'];
/**
* Split raw header text into unfolded name/value pairs. Stops at the first
* empty line (body separator). Returns a list of ['name' =>, 'value' =>].
*/
function parseHeaderLines(string $raw): array
{
$headers = [];
$current = null;
foreach (explode("\n", str_replace("\r\n", "\n", $raw)) as $line) {
if (trim($line) === '') break; // end of headers / blank separator
if ($current !== null && preg_match('/^[ \t]/', $line)) {
$headers[$current]['value'] .= ' ' . trim($line); // RFC 5322 folding continuation
continue;
}
$colon = strpos($line, ':');
if ($colon === false || $colon === 0) continue; // not a header line — skip garbage
$current = count($headers);
$headers[$current] = ['name' => trim(substr($line, 0, $colon)), 'value' => trim(substr($line, $colon + 1))];
}
return $headers;
}
/** All values for a header name, case-insensitive, in file order. */
function getHeaders(array $headers, string $name): array
{
$wanted = strtolower($name);
$out = [];
foreach ($headers as $header) {
if (strtolower($header['name']) === $wanted) $out[] = $header['value'];
}
return $out;
}
/** Extract an email address from a header value: prefers <addr>, falls back to the first bare address. */
function extractAddress(string $value): ?string
{
if (preg_match('/<([^<>\s]+)>/', $value, $m)) return $m[1];
return preg_match('/[^\s<>,;"\']+@[^\s<>,;"\']+/', $value, $m) ? $m[0] : null;
}
/** Parse an RFC 2822 date, ignoring trailing "(ZONE)" comments. Returns null when unparseable. */
function parseRfc2822Date(string $value): ?DateTimeImmutable
{
$cleaned = trim((string) preg_replace('/\([^)]*\)/', ' ', $value));
if ($cleaned === '') return null;
$dt = date_create_immutable($cleaned);
return $dt === false ? null : $dt;
}
/** Parse one Received header value into a hop (delay is filled in by parseHeaders). */
function parseReceived(string $value): array
{
$timestamp = null;
$lastSemi = strrpos($value, ';');
if ($lastSemi !== false) $timestamp = parseRfc2822Date(substr($value, $lastSemi + 1));
if ($timestamp === null) {
// Some clients omit the ';' — fall back to the first date-looking token.
if (preg_match('/\b(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s+[^\n]+/', $value, $m)) {
$timestamp = parseRfc2822Date($m[0]);
}
}
$trimDot = static function (?string $token): ?string {
return $token === null ? null : (string) preg_replace('/[.,]$/', '', $token);
};
$capture = static function (string $re) use ($value): ?string {
return preg_match($re, $value, $m) ? $m[1] : null;
};
return [
'from' => $trimDot($capture('/\bfrom\s+([^\s(;]+)/i')) ?? '',
'by' => $trimDot($capture('/\bby\s+([^\s(;]+)/i')) ?? '',
'timestamp' => $timestamp,
'delay' => null,
'protocol' => $capture('/\bwith\s+([^\s;()]+)/i') ?? '',
];
}
/**
* Parse Authentication-Results clauses, e.g.
* "mx.google.com; spf=pass smtp.mailfrom=a@b.com; dmarc=pass (p=REJECT) header.from=b.com".
*/
function parseAuthResults(array $values): array
{
$auth = [];
foreach (['spf', 'dkim', 'dmarc'] as $kind) {
$auth[$kind] = ['result' => 'none', 'domain' => null, 'selector' => null, 'policy' => null, 'detail' => null];
}
$token = static function (string $clause, string $key): ?string {
if (!preg_match('/\b' . $key . '=([^\s;)]+)/i', $clause, $m)) return null;
return (string) preg_replace('/[.,]$/', '', $m[1]);
};
foreach ($values as $value) {
foreach (explode(';', $value) as $rawClause) {
$clause = trim($rawClause);
$kind = null;
foreach (['spf', 'dkim', 'dmarc'] as $candidate) {
if (stripos($clause, $candidate . '=') === 0) { $kind = $candidate; break; }
}
if ($kind === null || $auth[$kind]['result'] !== 'none') continue; // first result wins
$target = ['result' => 'unknown', 'detail' => $clause, 'domain' => null, 'selector' => null, 'policy' => null];
if (preg_match('/=\s*([a-z]+)\b/i', $clause, $m)) $target['result'] = strtolower($m[1]);
if ($kind === 'spf') {
$target['domain'] = $token($clause, 'smtp.mailfrom') ?? $token($clause, 'mailfrom');
} elseif ($kind === 'dkim') {
$target['domain'] = $token($clause, 'header.d') ?? $token($clause, 'header.i');
$target['selector'] = $token($clause, 'header.s');
} else {
$target['domain'] = $token($clause, 'header.from');
if (preg_match('/\bp=([a-z]+)/i', $clause, $m)) $target['policy'] = strtolower($m[1]);
}
$auth[$kind] = $target;
}
}
return $auth;
}
/** Classic spoofing checks: sender mismatch, Reply-To misdirection, bulk mailers, chain gaps. */
function detectAnomalies(array $headers, array $hops): array
{
$anomalies = [];
$add = static function (string $type, string $severity, string $message) use (&$anomalies): void {
$anomalies[] = ['type' => $type, 'severity' => $severity, 'message' => $message];
};
$first = static function (string $name) use ($headers): string {
$values = getHeaders($headers, $name);
return $values === [] ? '' : $values[0];
};
$fromAddr = extractAddress($first('From'));
$returnPath = extractAddress($first('Return-Path'));
if ($fromAddr && $returnPath && strtolower($fromAddr) !== strtolower($returnPath)) {
$add('from-return-path-mismatch', 'critical', "Return-Path ({$returnPath}) does not match From ({$fromAddr}) — the envelope sender differs from the displayed sender. Common in spoofing and mailing-list relay.");
}
$replyTo = extractAddress($first('Reply-To'));
if ($fromAddr && $replyTo && strtolower($replyTo) !== strtolower($fromAddr)) {
$add('reply-to-mismatch', 'warning', "Reply-To ({$replyTo}) differs from From ({$fromAddr}) — replies would go to a different address than the visible sender.");
}
$xMailer = getHeaders($headers, 'X-Mailer');
$mailer = $xMailer === [] ? $first('User-Agent') : $xMailer[0];
if ($mailer !== '') {
$lower = strtolower($mailer);
foreach (EHA_SUSPICIOUS_MAILERS as $s) {
if (strpos($lower, $s) !== false) {
$add('suspicious-mailer', 'warning', "Mailer string \"{$mailer}\" contains a suspicious token (\"{$s}\") often seen in bulk sending tools.");
break;
}
}
}
foreach ($hops as $i => $hop) {
if ($hop['timestamp'] === null) {
$label = $hop['from'] !== '' ? $hop['from'] : ($hop['by'] !== '' ? $hop['by'] : 'unknown');
$add('hop-missing-timestamp', 'info', 'Hop ' . ($i + 1) . " ({$label}) has no parseable timestamp — delay for this leg cannot be computed.");
continue;
}
if ($i > 0 && $hops[$i - 1]['timestamp'] !== null) {
$delta = $hop['timestamp']->getTimestamp() - $hops[$i - 1]['timestamp']->getTimestamp();
if ($delta < 0) {
$add('negative-delay', 'warning', 'Hop ' . ($i + 1) . ' is timestamped ' . sprintf('%.1f', abs($delta)) . "s BEFORE hop {$i} — clock skew between servers or a forged Received header.");
}
}
}
if (getHeaders($headers, 'Authentication-Results') === []) {
$add('no-auth-results', 'info', 'No Authentication-Results header found — SPF/DKIM/DMARC status cannot be verified from this message.');
}
return $anomalies;
}
/** Parse raw email headers (RFC 5322): headers, chronological hops, auth verdicts, anomalies. */
function parseHeaders(string $raw): array
{
$headers = parseHeaderLines($raw);
// Received headers are listed newest-first; parse bottom-up so hops[0] is the oldest.
$hops = array_reverse(array_map('parseReceived', getHeaders($headers, 'Received')));
foreach ($hops as $i => $hop) {
if ($i > 0 && $hop['timestamp'] !== null && $hops[$i - 1]['timestamp'] !== null) {
$hops[$i]['delay'] = $hop['timestamp']->getTimestamp() - $hops[$i - 1]['timestamp']->getTimestamp();
}
}
return [
'headers' => $headers,
'hops' => $hops,
'auth' => parseAuthResults(getHeaders($headers, 'Authentication-Results')),
'anomalies' => detectAnomalies($headers, $hops),
];
}
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 →