719-286-0751 [email protected]

Add CDN URLs To Images, CSS, and Javascript using PHP

In this blog post, you’ll find a handy php function which you can use to easily apply your CDN (Content Delivery Network) domain to your existing static assets. This means all you have to do is run your HTML through the below function — no need to update any HTML by hand!

This function is great if you have already written a lot of HTML which you want the ability to serve from your CDN without hardcoding the change. The code will convert Javascript, CSS, and Image tags.

** Note that if you’re using a platform like Magento, there are built in BASE URL variables which should handle this for you. This code is meant for users who need to process CMS content, or are working inside a platform / framework which does not have an easy way to serve CDN assets.

To accomplish this, we use a few pcre regular expressions to match the below html tags:

  • <script> tags from our domain
  • <img> tags from our domain
  • <link href=> tags from our domain

We also check for any script, img, or link being served from a protocol relative (//domain.com) or relative (/path) URL.

Once we’ve matched the HTML tags we’re looking for, we then replace the src or href values on those tags to point to our CDN domain.

function useCdnUrls($html)
{
        $cdnUrl = "//cdn.domain.com";
        $baseUrl = "domain.com";

        /*
         * Remove all images or scripts that may be loaded with explicit domain
         * Match:
         * - http://domain.com/assets...
         * - https://domain.com/assets...
         * - //domain.com/assets...
         * - /assets...
         */
        $patterns = [

                // Match sources that are from the www or mobile urls
                // We check for the schema as well as protocol relative urls
            '~(<(img|script|link)[^>]*)(src|href) *= *(["\'])(https?:)?//(' . preg_quote($baseUrl) . ')~',

                // Match sources that just begin relative to the current domain
                // src="/assets/..."
                // Our regex matches the initial "/" character with a negative lookahead
                // ensuring the next character is not a slash
            '~(<(img|script|link)[^>]*)(src|href) *= *(["\'])/(?!/)~'
        ];

        $html = preg_replace_callback($patterns, function (array $matches) use ($cdnUrl) {

                //     <img|script...        '|"...         cdn url
                return $matches[1] . $matches[3] .  "=" . $matches[4] . $cdnUrl;
        }, $html);

        return $html;
}

You would call the function like so:


$html = '<img src="https://domain.com/test.jpg" />';
echo useCdnUrls($html);

// will output
// <img src="//cdn.domain.com/test.jpg" />

Notice that our function uses a protocol relative link for the CDN — this means the CDN will serve the correct HTTP schema regardless of whether you’re browsing in secure (https) or unsecure (http) mode.

Need Help Implementing a CDN?

Here at Cadence Labs, we’ve got years of experience optimizing websites, and can help you with adding a high-performance CDN to your site.

If you would like assistance implementing a CDN, call (719)-286-0751 or visit our contact page to have a real person contact you today!

Alan Barber is the Lead Web Developer at Cadence Labs and a Magento Certified developer.

 

1 Comment

  1. David Ruess

    Hi there,

    This is exactly what I’m looking to do, except I don’t know how to do it. I realize this is a newb questions, but how do I run my files through that function? In my head I’m thinking like I click a button and bop, out pops an html or php file with all the URL’s updated. But I have a feeling it doesn’t work that way.

    Do I need to type this around every asset that I have listed in my code?

    $html = ”;
    echo useCdnUrls($html);

    Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Install our webapp on your iPhone! Tap and then Add to homescreen.
Share This