CodeIgniter CDN Integration

The CodeIgniter CDN integration is fairly easy. This tutorial guides you through the required steps. It is important that you use the HTML helper and URL helper to include any static assets in your project (e.g. echo img(base_url('img/keycdn-logo.png'));). You need to specify the base_url variable in your config.php.

  1. First, we need to extend the current URL helper function. Edit the file application/config/config.php.
    /*
    |--------------------------------------------------------------------------
    | Class Extension Prefix
    |--------------------------------------------------------------------------
    |
    | This item allows you to set the filename/classname prefix when extending
    | native libraries.  For more information please see the user guide:
    |
    | http://codeigniter.com/user_guide/general/core_classes.html
    | http://codeigniter.com/user_guide/general/creating_libraries.html
    |
    */
    $config['subclass_prefix'] = 'ext.';
  2. Now you need to extend the existing base_url function by overwriting it. Create this file application/helpers/ext.url_helper.php.
    <?php
    
    /**
     * base_url
     *
     * Overwrites the base_url function to support
     * loading your asset from KeyCDN.
     */
    function base_url($uri)
    {
       $currentInstance =& get_instance();
    
       $keycdnUrl = $currentInstance->config->item('keycdn_url');
    
       $extensions = array('css', 'js', 'jpg', 'jpeg', 'png', 'gif','pdf');
       $pathParts = pathinfo($uri);
    
       if (!empty($keycdnUrl) && in_array($pathParts['extension'],$extensions)) {
          return $keycdnUrl . $uri;
       }
    
       return $currentInstance->config->base_url($uri);
    }
  3. Set the KeyCDN URL. Modify this file applicaiton/config/config.php and add the following code. Replace <your_zone_url> with your zone URL.
    /*
    |--------------------------------------------------------------------------
    | KeyCDN URL
    |--------------------------------------------------------------------------
    |
    | Loading content like .js, .png, .css files from KeyCDN.
    |
    |  http://demo-1.kxcdn.com/
    |
    | Still use the base_url() function to upload assets on your origin.
    |
    */
    $config['keycdn_url']   = '<your_zone_url>';
  4. Finally, verify the HTML source code if your assets are loading from KeyCDN.
    CodeIgniter CDN integration

Leave A Comment?