Absolute Path For Codeigniter

In an earlier post I spoke about a missing helper in Codeigniter.  An absolute path, particularly useful when handling images and files.

I think it is probably better to extend the core helper path.

Create a file applications/helpers/MY_path_helper.php

<?php
/**
 * Absolute Path
 *
 * Returns an absolute path based on your basepath.
 * Segments can be passed via the
 * first parameter either as a string.
 * ie absolute_path('uploads/images/cow/)
 * would
 *
 * @access    public
 * @param    string
 * @return    string
 */
if ( ! function_exists('absolute_path'))
{
    function absolute_path($path = '')
    {
        $abs_path = str_replace('system/',$path, BASEPATH);
        //Add a trailing slash if it doesn't exist.
        $abs_path = preg_replace("#([^/])/*$#", "\\1/", $abs_path);
        return $abs_path;
    }
}

You can now call this function anywhere (provided you have loaded the helper).

print absolute_path();

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>