David Ericsson
David Ericsson

Reputation: 2660

Returning the URL where a script is installed

I need to find out dynamically the base url of a script. Let's say I have installed a script in the folder script, the base url of the script would be http://www.example.com/script, let's say I place it in the root it has to be http://www.example.com

Is there a way to find this out dynamically?

Using basename(__DIR__), or basename(__FILE__), getcwd() won't bring me the desired results.

Tried stuff similar to echo $_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']); but this of course always gives back the current page url.

I want to declare a constant called ROOT_URL in my index.php (everything gets loaded by this file), so I can use this constant in any wished project.

Upvotes: 0

Views: 84

Answers (3)

David Ericsson
David Ericsson

Reputation: 2660

Got it fixed with the help of Anthony

Changed his first submitted method a bit :

  public static function RealDirname($path)
{
    $path = dirname($path);

    if($path[0] == '\\') //Windows servers tend to mess up [everything]
        $path[0] = '/';

    $lastChar = strlen($path) - 1;
    if($path[$lastChar] != '/')
        $path .= '/';

    return $path;
}

public static function getAbsolutePath()
{
        $path = (isset($_SERVER['HTTPS']) ? 'https://' :'http://').$_SERVER['HTTP_HOST'];
        $path = $path.self::RealDirname($_SERVER['PHP_SELF']);
        return substr($path, 0, strpos($path, "index.php"));

}  

Strips out everything after the index.php and gives me back the root.

Upvotes: 0

Anthony Teisseire
Anthony Teisseire

Reputation: 593

I had to cover the same issue a few weeks ago in my MVC implementation.

There you go :

public static function RealDirname($path)
{
    $path = dirname($path);

    if($path[0] == '\\') //Windows servers tend to mess up
        $path[0] = '/';

    $lastChar = strlen($path) - 1;
    if($path[$lastChar] != '/')
        $path .= '/';

    return $path;
}

public static function GetAbsolutePath()
{
            global $config;

    if(empty($config["base_path"]))
        $config["base_path"] = self::GetDomainURL();

    return $config["base_path"].(self::RealDirname($_SERVER['PHP_SELF']));
}

public static function GetDomainURL()
{
    return (isset($_SERVER['HTTPS']) ? 'https://' :'http://').$_SERVER['HTTP_HOST'];
}

Just call getAbsolutePath, and this should return you the whole path with the URL :)

Tried on a page located at :

http://localhost:8080/old/test.php

GetAbsolutePath returned :

http://localhost:8080/old/

And GetDomainURL :

http://localhost:8080

Upvotes: 1

Red Cricket
Red Cricket

Reputation: 10470

Have you tried $script_filename = $_SERVER['SCRIPT_FILENAME']; You can have a look here http://php.net/manual/en/reserved.variables.server.php

Upvotes: 0

Related Questions