getButterfly Logo getButterfly

This is an advanced solution used to redirect old links using 301 (or 302, or 504 or whatever code you need) to new links using native PHP functions. If they don’t work, the redirection falls back to an HTML meta refresh. Enjoy!

PHP Redirection

<?php
/**
 * PHP Redirects
 *
 * @copyright Copyright (c) 2016 getbutterfly.com getButterfly (https://getbutterfly.com)
 * @license https://getbutterfly.com New BSD License
 */

/**
 * Checks and cleans a URL.
 *
 * A number of characters are removed from the URL.
 *
 * @param string $url The URL to be cleaned.
 * @return string The cleaned $url.
 */
function php_deep_replace($search, $subject) {
    $subject = (string) $subject;

    $count = 1;

    while($count) {
        $subject = str_replace($search, '', $subject, $count);
    }

    return $subject;
}

function php_esc_url($url) {
    $original_url = $url;

    if('' == $url)
        return $url;

    $url = str_replace( ' ', '%20', $url );
    $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\[\]\\x80-\\xff]|i', '', $url);

    if('' === $url) {
        return $url;
    }

    if(0 !== stripos( $url, 'mailto:')) {
        $strip = array('%0d', '%0a', '%0D', '%0A');
        $url = php_deep_replace($strip, $url);
    }

    $url = str_replace(';//', '://', $url);
    /* If the URL doesn't appear to contain a scheme, we
     * presume it needs http:// prepended (unless a relative
     * link starting with /, # or ? or a php file).
     */
    if(strpos($url, ':') === false && !in_array($url[0], array('/', '#', '?')) && !preg_match('/^[a-z0-9-]+?\.php/i', $url))
        $url = 'http://' . $url;

    // Replace ampersands and single quotes only when displaying.
    $url = str_replace('&amp;', '&#038;', $url);
    $url = str_replace("'", '&#039;', $url);

    /**
     * Filter a string cleaned and escaped for output as a URL.
     *
     * @param string $_context
     */
    return $url;
}

function php_redirect($url) {
    // Sanitize URI
    $url = php_esc_url($url);

    // Get and append query string
    if(!empty($_SERVER['QUERY_STRING'])) {
        $url .= '?' . $_SERVER['QUERY_STRING'];
    }

    $content = sprintf('<!doctype html><html class="no-js"><head><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=%1$s"><title>Redirecting to %1$s...</title></head><body>Redirecting to <a href="%1$s">%1$s</a>...</body></html>', htmlspecialchars($url, ENT_QUOTES, 'UTF-8'));

    header('Location: ' . $url, true, 301);
    die($content);
}

/**
* Get client URI including arguments.
*/
$getUri = php_esc_url($_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);

if(strpos($getUri, 'example.com/old-uri-1') !== false) {
    php_redirect('https://www.example.com/new-uri-1');
} else if(strpos($getUri, 'example.com/old-uri-2') !== false) {
    php_redirect('https://www.example.com/new-uri-2');
} else if(strpos($getUri, 'example.com/old-uri-3') !== false) {
    php_redirect('https://www.example.com/new-uri-3');
}

And just go on with the loop. If you need to integrate it into your CMS, you can use a foreach() function and loop through your database.


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

Leave a reply