Skip to content

PHP Convert href to absolute url

PHP Convert href to absolute url

Not fully tested, but the idea/concept is there.
public function convert_href_to_url($href)
{
    // Check if it's already a valid url
    if( strncmp($url, 'http', 4) === 0 )
        return $href;
    
    // Relative path (//) 
    if( strncmp($url, '//', 2) === 0 ) {
        $https 	  = isset($_SERVER['HTTPS']);
        $protocol = $https ? "https://" : "http://";
        $domain   = $_SERVER['HTTP_HOST']; // or fallback to SERVER_NAME 
        $url 	  = $protocol . $domain . $href;
                return $url;
    }

    if( strncmp($url, '/', 1) === 0 ) {
        // Relative path to current domain
        $domain = $_SERVER['HTTP_HOST']; // or fallback to SERVER_NAME 
        $protocol = "http://";
        $url 	  = $protocol . $domain . $href;
        return $url;
    }
    
    return "Are you sure it's a valid href ?";
}
 
Enjoyed the content ? Share it with your friends !
Published inDevelopmentProgramming

Be First to Comment

Leave a Reply

Your email address will not be published.