Drew Baker
Drew Baker

Reputation: 14430

PHP - Determine if a URL is an internal or external URL

This is a self Q&A

I found myself often needing to parse a URL supplied by a CMS user to determine if it's an external URL, or an internal one. Often clients want external URL's to be highlighted differently, or to force target="_blank" for them.

So, I want a piece of code that can parse a URL and determine if it's an internal or external URL, and then return a different class and target for either scenario.

Upvotes: 0

Views: 3867

Answers (1)

Drew Baker
Drew Baker

Reputation: 14430

This below code takes a URL as a string, then two different class names as strings and compares the URL to the host (I also commented out a WordPress specific piece of code if needed).

function parse_external_url( $url = '', $internal_class = 'internal-link', $external_class = 'external-link') {

    // Abort if parameter URL is empty
    if( empty($url) ) {
        return false;
    }

    // Parse home URL and parameter URL
    $link_url = parse_url( $url );
    $home_url = parse_url( $_SERVER['HTTP_HOST'] );     
    //$home_url = parse_url( home_url() );  // Works for WordPress


    // Decide on target
    if( empty($link_url['host']) ) {
        // Is an internal link
        $target = '_self';
        $class = $internal_class;

    } elseif( $link_url['host'] == $home_url['host'] ) {
        // Is an internal link
        $target = '_self';
        $class = $internal_class;

    } else {
        // Is an external link
        $target = '_blank';
        $class = $external_class;
    }

    // Return array
    $output = array(
        'class'     => $class,
        'target'    => $target,
        'url'       => $url
    );
    return $output;
}

You would use the code like this:

$url_data = parse_external_url( 'http://www.funkhaus.us', 'internal-link-class', 'external-link-class' );
<a href="<?php echo $url_data['url']; ?>" target="<?php echo $url_data['target']; ?>" class="<?php echo $url_data['class']; ?>">This is a link</a>

Upvotes: 4

Related Questions