Skip to content
← Back to Snippets
Code

Set HTTP Response Code

Sets an allowed HTTP response code with http_response_code() after validating the code against a small explicit allowlist.

Purpose

Sets an allowed HTTP response code with http_response_code() after validating the code against a small explicit allowlist.

Snippet details

ContextHttpLevelPracticalCopy-and-paste statusMarked safe after review.

Categories

  • APIs and Webhooks

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

/**
 * Set HTTP Response Code.
 *
 * Purpose:
 * Sends a controlled HTTP status code after checking it against an explicit
 * allowlist used by the application.
 *
 * @param int $status_code Requested HTTP status code.
 * @return array Selected status code and message.
 */
function ogSnippetSetHttpResponseCode(int $status_code): array {
	$allowed_codes = array(
		200 => 'OK',
		301 => 'Moved Permanently',
		302 => 'Found',
		400 => 'Bad Request',
		403 => 'Forbidden',
		404 => 'Not Found',
		500 => 'Internal Server Error'
	);

	if (array_key_exists($status_code, $allowed_codes) === false) {
		$status_code = 500;
	}

	if (headers_sent() === false) {
		http_response_code($status_code);
	}

	return array(
		'status_code' => $status_code,
		'message' => $allowed_codes[$status_code]
	);
}

$response_report = ogSnippetSetHttpResponseCode(404);

echo 'HTTP status: '.$response_report['status_code'].' '.$response_report['message'];