PHP: building a URL path

Try this:

$base = "http://foo.com";
$subfolder = "product/data";
$filename = "foo.xml";

function stripTrailingSlash(&$component) {
    $component = rtrim($component, '/');
}
$array = array($base, $subfolder, $filename);
array_walk_recursive($array, 'stripTrailingSlash'); 
$url = implode('/', $array);

when it comes down to something like this I like to use a special function with unlimited parameters.

define('BASE_URL','http://mysite.com'); //Without last slash
function build_url()
{
    return BASE_URL . '/' . implode(func_get_args(),'/');
}

OR

function build_url()
{
    $Path = BASE_URL;
    foreach(func_get_args() as $path_part)
    {
        $Path .= '/' . $path_part;
    }
    return $Path;
}

So that when I use the function I can do

echo build_url('home'); //http://mysite.com/home
echo build_url('public','css','style.css'); //http://mysite.com/public/css/style.css
echo build_url('index.php'); //http://mysite.com/index.php

hope this helps you, works really well for me especially within an Framework Environment.

to use with params you can append the url like so for simplicity.

echo build_url('home') . '?' .  http_build_query(array('hello' => 'world'));

Would produce: http://mysite.com/home?hello=world

Tags:

Php