PHP redirect URL


Use header to redirect to another URL in PHP:

header('Location: https://remarkablemark.org/');
exit;

Here’s a function that redirects to another URL:

/**
 * Redirects to URL.
 */
function redirect(string $url): void
{
    header('Location: ' . $url);
    exit;
}

And here’s an updated function that redirects to an absolute URL if the URL is valid:

/**
 * Redirects to absolute URL if valid.
 */
function redirect(string $url): void
{
    if (filter_var($url, FILTER_VALIDATE_URL)) {
        header('Location: ' . $url);
        exit;
    }
}


If you enjoyed this post, please consider supporting this site!