Skip to content
← Back to Snippets
Code

Redacted Audit Context Builder

Builds an audit-log context array while redacting sensitive fields before the data is stored or displayed.

Purpose

Builds an audit-log context array while redacting sensitive fields before the data is stored or displayed.

Snippet details

ContextAuditLevelAdvancedCopy-and-paste statusMarked safe after review.

Categories

  • Security

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Redacted Audit Context Builder.
 *
 * Purpose:
 * Creates an audit context array with sensitive values removed before logging.
 *
 * @param array $context Raw audit context.
 * @param array $sensitive_keys Field names that must be redacted.
 * @return array Redacted audit context.
 */
function ogSnippetRedactedAuditContextBuilder(array $context, array $sensitive_keys): array {
	$redacted_context = array();
	$sensitive_lookup = array();

	foreach ($sensitive_keys as $key) {
		$sensitive_lookup[strtolower((string) $key)] = true;
	}

	foreach ($context as $key => $value) {
		$normalized_key = strtolower((string) $key);

		if (isset($sensitive_lookup[$normalized_key]) === true) {
			$redacted_context[$key] = '[redacted]';
		} elseif (is_array($value) === true) {
			$redacted_context[$key] = ogSnippetRedactedAuditContextBuilder($value, $sensitive_keys);
		} elseif (is_scalar($value) === true || $value === null) {
			$redacted_context[$key] = $value;
		} else {
			$redacted_context[$key] = '[unsupported value]';
		}
	}

	return $redacted_context;
}

$audit_context = array(
	'actor' => 'jedi-admin',
	'action' => 'license-review',
	'password' => 'do-not-log-this',
	'payload' => array(
		'token' => 'do-not-log-this-either',
		'asset' => 'falcon-drive-core'
	)
);
$redacted_audit = ogSnippetRedactedAuditContextBuilder($audit_context, array('password', 'token'));

echo 'Star Wars audit actor: '.$redacted_audit['actor'];