[rb]Get relative url with symfony

While using symfony in a subdirectory of your domain you might want to get the absolute URL path of you web directory. This should help you:

function getUrlLocation() {
	$s = $_SERVER['DOCUMENT_ROOT'];
	$t = explode(DIRECTORY_SEPARATOR, sfConfig::get('sf_web_dir'));
	$tx = explode(DIRECTORY_SEPARATOR,$s);
	$dif = array_diff($t,$tx);
	return implode(DIRECTORY_SEPARATOR, $dif);
}

A practical example would be redirecting from a public module to the backend module for example. That would be accomplished by using the following code:

header("Location: /". getUrlLocation() . "/backend.php"); exit();

One thought on “[rb]Get relative url with symfony”

  1. This does not work as expected on a windows server.
    My DOCUMENT_ROOT and sf_web_dir is:
    string ‘C:/wamp/www’ (length=11)
    string ‘C:wampwwwprojectweb’ (length=23)
    And getUrlLocation() returns:
    string ‘C:wampwwwprojectweb’ (length=23)

    You could fix your function, but symfony already has this functioniality:
    function get_base_url() {
    $request = sfContext::getInstance()->getRequest();
    return $request->getRelativeUrlRoot();
    }
    This returns: string ‘/project/web’ (length=12)

    If you want the absolute URL with http://servername/…, use this:
    function get_base_url() {
    $request = sfContext::getInstance()->getRequest();
    return $request->getUriPrefix() . $request->getRelativeUrlRoot();
    }
    string ‘http://localhost/project/web’ (length=28)

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=""> <s> <strike> <strong>