Skip to content
← Back to Snippets
Code

Download Header Policy Plan

Prepares safe download headers for approved files while rejecting inline execution and unsafe filenames.

Purpose

Prepares safe download headers for approved files while rejecting inline execution and unsafe filenames.

Snippet details

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

/**
 * Download Header Policy Plan.
 *
 * Purpose:
 * Prepares safe download headers for approved files while rejecting inline execution and unsafe filenames.
 *
 * @param string $download_name Public download filename.
 * @param string $mime_type Approved MIME type.
 * @param int $byte_size File size in bytes.
 * @return array Download header policy.
 */
function ogSnippetDownloadHeaderPolicyPlan(string $download_name, string $mime_type, int $byte_size): array {
	$safe_name = basename($download_name);
	$safe_name = preg_replace('/[^a-zA-Z0-9._-]/', '-', $safe_name);
	$headers = array();
	$headers[] = 'Content-Type: '.$mime_type;
	$headers[] = 'Content-Length: '.$byte_size;
	$headers[] = 'Content-Disposition: attachment; filename="'.$safe_name.'"';
	$headers[] = 'X-Content-Type-Options: nosniff';
	return array('filename' => $safe_name, 'headers' => $headers, 'inline_allowed' => false);
}

$download_policy = ogSnippetDownloadHeaderPolicyPlan('weyland-report.pdf', 'application/pdf', 71200);
echo $download_policy['filename'];