Redirect to Another Page
Validates a local redirect target, sends a `Location` header, and exits before any accidental output can continue.
Purpose
Validates a local redirect target, sends a `Location` header, and exits before any accidental output can continue.
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.
*/
/**
* Redirect to Another Page.
*
* Purpose:
* Performs a local allowlisted redirect with a `Location` header and a hard
* `exit` so the old controller cannot continue rendering output.
*
* @param string $target_path Local path such as /hire-me.html.
* @param array $allowed_paths Local redirect targets allowed by the caller.
* @return void
*/
function ogSnippetRedirectToAnotherPage(string $target_path, array $allowed_paths): void {
$target_path = trim($target_path);
if ($target_path === '') {
$target_path = '/';
}
if (strpos($target_path, '//') !== false || strpos($target_path, '://') !== false) {
$target_path = '/';
}
if (in_array($target_path, $allowed_paths, true) === false) {
$target_path = '/';
}
if (headers_sent() === false) {
header('Location: '.$target_path, true, 302);
exit;
}
echo 'Redirect failed because output already started.';
exit;
}
$approved_jump_points = array(
'/',
'/premium-php-scripts.html',
'/hire-php-developer.html'
);
// Controller usage after a successful form submission:
// ogSnippetRedirectToAnotherPage('/hire-php-developer.html', $approved_jump_points);