Skip to content
← Back to Snippets
Code

Get File Extension

Extracts and normalizes a file extension from a filename, then checks it against an approved extension list.

Purpose

Extracts and normalizes a file extension from a filename, then checks it against an approved extension list.

Snippet details

ContextFileLevelProductionCopy-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 File Extension.
 *
 * Purpose:
 * Reads a filename, extracts the final extension with pathinfo(), normalizes it
 * to lowercase, and checks it against an allowlist.
 *
 * @param string $file_name Filename or path supplied by the application.
 * @param array $allowed_extensions Lowercase extension allowlist.
 * @return array Extension details and allowlist status.
 */
function ogSnippetGetFileExtension(string $file_name, array $allowed_extensions = array('jpg', 'jpeg', 'png', 'webp', 'pdf')): array {
	$clean_name = trim($file_name);

	if ($clean_name === '') {
		return array(
			'success' => false,
			'extension' => '',
			'allowed' => false,
			'message' => 'A filename is required.'
		);
	}

	$base_name = basename($clean_name);
	$extension = pathinfo($base_name, PATHINFO_EXTENSION);
	$extension = strtolower($extension);

	if ($extension === '') {
		return array(
			'success' => true,
			'extension' => '',
			'allowed' => false,
			'message' => 'The filename has no extension.'
		);
	}

	$normalized_allowlist = array();
	foreach ($allowed_extensions as $allowed_extension) {
		$allowed_extension = strtolower(trim((string) $allowed_extension));
		if ($allowed_extension !== '') {
			$normalized_allowlist[] = $allowed_extension;
		}
	}

	$allowed = in_array($extension, $normalized_allowlist, true);
	$message = 'Extension is not allowed.';

	if ($allowed === true) {
		$message = 'Extension accepted.';
	}

	return array(
		'success' => true,
		'filename' => $base_name,
		'extension' => $extension,
		'allowed' => $allowed,
		'message' => $message
	);
}

/*
$result = ogSnippetGetFileExtension('enterprise-refit.NCC1701.PNG', array('png', 'webp'));
print_r($result);
*/