Skip to content
← Back to Snippets
Code

Get Server Information from $_SERVER

Reads an allowlisted subset of `$_SERVER`, normalizes common request values, and avoids dumping sensitive server internals.

Purpose

Reads an allowlisted subset of `$_SERVER`, normalizes common request values, and avoids dumping sensitive server internals.

Snippet details

ContextServerLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

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.
 */

/**
 * Get Server Information from $_SERVER.
 *
 * Purpose:
 * Reads only a safe allowlisted subset of `$_SERVER` values for display,
 * logging, diagnostics, or controller decisions.
 *
 * @param array $server_values Usually `$_SERVER`.
 * @return array Normalized server/request information.
 */
function ogSnippetGetServerInformation(array $server_values): array {
	$request_method = '';
	$host_name = '';
	$request_uri = '';
	$server_protocol = '';
	$is_https = false;

	if (isset($server_values['REQUEST_METHOD']) === true) {
		$request_method = strtoupper(trim((string) $server_values['REQUEST_METHOD']));
	}

	if (isset($server_values['HTTP_HOST']) === true) {
		$host_name = strtolower(trim((string) $server_values['HTTP_HOST']));
	}

	if (isset($server_values['REQUEST_URI']) === true) {
		$request_uri = trim((string) $server_values['REQUEST_URI']);
	}

	if (isset($server_values['SERVER_PROTOCOL']) === true) {
		$server_protocol = trim((string) $server_values['SERVER_PROTOCOL']);
	}

	if (isset($server_values['HTTPS']) === true && $server_values['HTTPS'] === 'on') {
		$is_https = true;
	}

	return array(
		'request_method' => $request_method,
		'host_name' => $host_name,
		'request_uri' => $request_uri,
		'server_protocol' => $server_protocol,
		'is_https' => $is_https
	);
}

$server_report = ogSnippetGetServerInformation($_SERVER);

echo 'Request method: '.$server_report['request_method'];