Skip to content
← Back to Snippets
Code

Send a JSON HTTP Header

Sets an HTTP status code and JSON content type header before encoding an API response payload.

Purpose

Sets an HTTP status code and JSON content type header before encoding an API response payload.

Snippet details

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

/**
 * Send a JSON HTTP Header.
 *
 * Purpose:
 * Sends a JSON response with an explicit HTTP status code and a predictable
 * encoded payload.
 *
 * @param array $payload Data to encode as JSON.
 * @param int $status_code HTTP response status code.
 * @return string Encoded JSON response body.
 */
function ogSnippetSendAJsonHttpHeader(array $payload, int $status_code): string {
	if ($status_code < 100 || $status_code > 599) {
		$status_code = 200;
	}

	$response_body = json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);

	if ($response_body === false) {
		$status_code = 500;
		$response_body = '{"ok":false,"error":"json_encoding_failed"}';
	}

	if (headers_sent() === false) {
		http_response_code($status_code);
		header('Content-Type: application/json; charset=UTF-8');
		header('X-Content-Type-Options: nosniff');
	}

	return $response_body;
}

$expanse_api_payload = array(
	'ok' => true,
	'ship' => 'Rocinante',
	'action' => 'transponder-check',
	'status' => 'green'
);

echo ogSnippetSendAJsonHttpHeader($expanse_api_payload, 200);